# Question
Title: How can I associate a key_callback with a wrapper class instance?
I'm trying to wrap my GLFW3 calls into a single class:

```
class WindowManager {
private:
    GLFWwindow* window_;
    GLFWmonitor* monitor_;
    Keyboard* keyboard_;
...
}

```

And I'm trying to setup a singleton keyboard class that collects the keys presses during execution. In GLFW I can set a `key_callback` function that is outside the class definition (a free function):

```
WindowManager::WindowManager() {
    ...
    glfwSetKeyCallback(window_, key_callback);
    ...
}

// not a class function
void key_callback(GLFWwindow* window, int key, int scan code, int action, int mods) {
    ...
}

```

How can I associate my callback and my `WindowManager` instance so that I can set the `keyboard_` object values? I cannot make the `key_callback` a member function of `WindowManager` because that would not work since that function would be a member of the the WindowManager class and in C++ member function of a class get their names dangled.

# Answer
I had a similar problem to this. It's annoying that there's so little documentation on using glfwSetWindowUserPointer and glfGetWindowUserPointer. Here's my solution to your problem:

```
WindowManager::WindowManager() {
    // ...
    glfwSetUserPointer(window_, this);
    glfwSetKeyCallback(window_, key_callback_);
    // ...
}

void WindowManager::key_callback(GLFWwindow *window, int, int ,int, int) {
    WindowManager *windowManager =
      static_cast<WindowManager*>(glfwGetUserPointer(window));
    Keyboard *keyboard = windowManager->keyboard_;

    switch(key) {
        case GLFW_KEY_ESCAPE:
             keyboard->reconfigure();
             break;
     }
}

```

Anyway, as this is one of the top results for using GLFW with C++ classes, I will also provide my method of encapsulating a glfwWindow in a C++ class. I think that this is the most elegant way to do it, as it avoids having to use globals, singletons or unique\_ptrs, lets the programmer manipulate the window in a much more OO/C++-y style, and allows subclassing (at the cost of a slightly more cluttered header file).

```
// Window.hpp
#include <GLFW/glfw3.h>
class Window {
public:
    Window();
    auto ViewportDidResize(int w, int h)             -> void;
    // Make virtual you want to subclass so that windows have
    // different contents. Another strategy is to split the
    // rendering calls into a renderer class.
    (virtual) auto RenderScene(void)                 -> void;
    (virtual) auto UpdateScene(double ms)            -> void;
    // etc for input, quitting
private:
    GLFWwindow *m_glfwWindow;

    // Here are our callbacks. I like making them inline so they don't take up
    // any of the cpp file
    inline static auto WindowResizeCallback(
        GLFWwindow *win,
        int w,
        int h) -> void {
            Window *window = static_cast<Window*>(glfwGetUserPointer(win));
            window->ViewportDidResize(w, h);
    }
    inline static auto WindowRefreshCallback(
        void) -> void {
            Window *window = static_cast<Window*>(glfwGetUserPointer(win));
            window->RenderScene(void);
    }
    // same for input, quitting
}

```

And for:

```
// Window.cpp
#include <GLFW/glfw3.h>
#include "Window.hpp"
Window::Window() {
    // initialise glfw and m_glfwWindow,
    // create openGL context, initialise any other c++ resources
    glfwInit();
    m_glfwWindow = glfwCreateWindow(800, 600, "GL", NULL, NULL);

    // needed for glfwGetUserPointer to work
    glfwSetWindowUserPointer(m_glfwWindow, this);

    // set our static functions as callbacks
    glfwSetFramebufferSizeCallback(m_glfwWindow, WindowResizeCallback);
    glfwSetWindowRefreshCallback(m_glfwWindow, WindowRefreshCallback);
}

// Standard window methods are called for each window
auto
Window::ViewportDidResize(int w, int h) -> void
{
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
}

```

This can probably be quite easily integrated with a WindowManager/InputManager class, but I think it's easier to just have each window manage itself.
> 13 votes

# Answer
The callbacks must be free functions or static functions, as you've found out. The callbacks take a `GLFWwindow*` as their first argument in place of an automatic `this` pointer.

With GLFW you can use `glfwSetWindowUserPointer` and `glfwGetWindowUserPointer` to store and retrieve a reference to `WindowManager` or a per-window `Window` instance.

Remember that GLFW doesn't use virtual functions any kind of direct polymorphism as it's a pure C API. Such APIs *always* assume free functions (C has no classes or member functions at all, virtual or otherwise) and pass explicit "object instances" as parameters (usually as the first parameter; C has no `this`). Good C APIs also include the user pointer functionality (sometimes called "user data" among other things) so you don't have to use globals.

---

**Old answer:**

If you need to access other data in your `WindowManager` (or other systems), you might need to have them be globally accessible if you want to access it from callbacks. For instance, have a global `std::unique_ptr<Engine>` that you can use to access your window manager, or just make a global `std::unique_ptr<WindowManager>` (replace `std::unique_ptr` with something "better for singletons" if you wish).

If you want multiple window support, you'll also then have `WindowManager` contain some data structure to map `GLFWwindow*` values to your own `Window` classes in some way, e.g. using a `std::unordered_map` or the like. Your callback could then access the global and query the data structure using the `GLFWwindow*` they received to look up the data they need.
> 6 votes

---
Tags: c++, glfw
---


# Question
Title: How can I handle the combination of multiple shader effects?
To be able to work efficiently with effects, is there a good way to combine multiple reusable "base" effects to achieve a more complex final result?

For example, say I have an effect that handles multi-texturing and one that handles ambient lighting. I'd like to combine them to achieve a final "ambient-lit multi-textured" effect.

This seems troublesome unless effects somehow can share information. When I just use the multi-texturing effect, I get the result I want. But when I afterwards apply the ambient lighting effect to intensify the color some value, it uses just uses the color from the ambient effect.

Is there a way to solve this? So that each effect can be individual and somehow not screw up the other effect? Or do I have to resort to manually writing one large effect file that lacks any flexibility?

# Answer
You have two broad approaches.

* You can use multiple effects, making multiple draw calls per model and switching effects between each. This is straightforward and would probably handle your simple multi-texturing and ambient shader combinations, and others like it, fairly easily. The trick is that you have to adjust the pipeline's blend mode between each shader (and possibly also modify the alpha outputs in the shaders) in order not to simply stamp over a previous draw's results. Because blend modes are not very configurable, this becomes constricting very fast.
* You can use a single effect, with everything you want it to do combined into a single shader. This is basically what you were assuming was the answer, but you *can* do it in an achievable fashion. The trick is to split up the effect early, before it is an actual shader.

The first approach is cumbersome and I won't speak on it further. The second approach is more common these days, and there are a variety of ways to implement it.

The super-shader (or "ubershader") approach was popular for a while. This method basically involves you, the programmer, writing a single massive shader that "does everything," but with particular bits of the shader's functionality wrapped in preprocessor macros or some other kind of guard. For example:

```
color = input.color;
#if USE_DIFFUSE_LIGHT
color = ComputeDiffuseLighting(color, normal, light_position);
#endif

#if USE_TEXTURING
color = (0.5 * color) + (0.5 * ComputeTextureColor(texture_coordinates))
#endif

```

Then you can create multiple *actual* shaders by recompiling this super-shader with various pieces turned on or off (you can either brute-force all permutations or you can intelligently preprocess all your materials to determine which combinations would be required). This way you always have a broad overview, as a programmer, of all the possible ways in which your different shader features would interact, but you also don't have to manually re-create tons of variations on very similar shaders. Here's another paper on the subject.

These days the hot trend is visual shader graphs and editors, such as ShaderForge for Unity.

The basic premise behind this approach (which is my favorite, with some caveats), is similar to the super-shader approach in that you are ultimately one final shader out of pieces. Instead, however, you the programmer author each small shader fragment independently, usually in some intermediate language or data structure of your own choosing (so you can understand the input and output variables of each fragment, and so on). Then you create a tool that allows an artist (or yourself) to string together these isolated fragments however you choose, and you post-process that graph (usually via a topological sort) into a final effect file you can feed your graphics API.

McGuire's Abstract Shade Trees paper is a good read on one way to build a shader tree system.

An interesting point about the shader tree approach is that you can choose the granularity of the nodes in your system. In some systems, nodes are almost always simple operations like "add" or "interpolate" or similar. In others, they can be very high level such as "bump map" or "cel shading." Or you can choose an in-between approach. The technique is particularly well suited to data-driven iteration, which is really nice, but it also requires a much higher up-front investment of time and technology before you can really utilize it, especially compared to the super-shader approach which can be done with a few crude regular expressions or text processing code fragments even if you don't have an actual C-style preprocessor available to you.
> 2 votes

---
Tags: xna, shaders, hlsl, lighting, effect
---


# Question
Title: How can I track how "well-lit" a player is so that I can determine if my AI can see him or her?
I want to see how well-lit the player character is in an environment so that my AI can react (or not) to the player when he or she is visible.

Currently I am doing this by reading back the color data of the final render target and computing the brightness of the player's region. It seems expensive and taxing, so I was wondering if there is a better way to approach this?

# Answer
> 3 votes
It can seem attractive to handle this kind of problem by reading back the brightness data -- after all, you're already rendering that information and so it will already be there, available, and up-to-date.

Unfortunately, it's probably not the best way to do it. Reading back data from the GPU isn't particularly fast or well-suited to this kind of operation. You are better off solving the visibility problem *entirely* on the CPU and basing it entirely off game data instead of graphics data.

You already know where all your lights are in the game world, and where the player is (since you're currently rendering them). A much more efficient approach to determining if the player is visible is to:

* Collect all the lights within a reasonable distance to the player (everything close enough to possibly illuminate the player). You can optimize this with some form of spatial partitioning of your game data, but if you have few enough lights per level you can also just brute-force it.
* For every light, apply the light's attenuated value to the player's total "lit" value.
* If the total "lit" value of the player exceeds some threshold, the player is visible. Otherwise the player is hidden in the shadows.

Not only will this be much more straightforward and faster than doing a read-back, it will allow you to tie in line-of-sight visibility checks if you want, as well.

---
Tags: xna
---


# Question
Title: Farseer - Difference between Position, GetLocalVector, and GetWorldVector
I have used Box2D extensively, and am used to just calling `body.GetPosition()`. But Farseer does not have this. Instead it has a property `Position`, as well as methods `GetLocalVector` and `GetWorldVector`. Farseer seemingly has a complete lack of documentation, and I have been unable to figure out what the difference is.

Also, though I feel a bit dumb about it, I don't really get what `GetWorldVector` means as opposed to `GetLocalVector`. They take a `localVector` and a `worldVector` as their respective arguments, but what does that mean? What is the difference between local and world vectors?

Any help is appreciated.

# Answer
> 2 votes
Ok, so obviously `Position` is simply the position of the `Body` in the world.

In order to fully explain `GetLocalVector` and `GetWorldVector`, I will also explain the `GetLocalPoint` and `GetWorldPoint` methods.

As you say, Farseer's documentation is not great. My advice is to build it from source within your own Solution, so you can easily investigate what's going on - and even tweak it to suit your needs.

Each `Body` in Farseer has a **transform** (`_xf`) made up of a **position** (`_xf.p`) and a **rotation** (`_xf.q`).

Knowing this, we can look at the four methods in question:

```
// GetLocalVector
return MathUtils.MulT(_xf.q, worldVector);

// GetLocalPoint
return MathUtils.MulT(ref _xf, worldPoint);

// GetWorldVector
return MathUtils.Mul(_xf.q, localVector);

// GetWorldPoint
return MathUtils.Mul(ref _xf, ref localPoint);

```

As you may know, when you multiply a point by a transformation matrix you are transforming it from one space into another. The transformation in this case transforms from the the local space of the body (where you specify your `Fixture`s, where `Vector2.Zero` is the origin of the body) into world space. (The **`World`** variants.)

Because the matrices in these cases are orthogonal, multiplying by the transpose (`MulT`) is the same as multiplying by the inverse. And, as you might expect, multiplying by the inverse performs the transform in the opposite direction (in this case: from world space into local space). (The **`Local`** variants.)

The variants (**`Vector`**) that only use the rotation (`_xf.q`) are for use with relative positions, and directions, where including an absolute offset in the transformation does not make sense.

**If that explanation went over your head, let me try some examples:**

Say your body has some kind of turret on it for firing weapons, offset from the body's origin. You would use `GetWorldPoint(muzzlePosition)` when you fire the weapon to figure out where in the world the projectile should be spawned. You would use `GetWorldVector(muzzleVelocity)` to set the velocity of the fired projectile.

Say your body is clickable. You would use `GetLocalPoint(worldMousePosition)` to find out the position on the body that was clicked. (Transforming the mouse position into world space is left as an exercise.)

Say you have many versions of the sprite that represents your body - each lit from a different direction. You would use the output of `GetLocalVector(sunlightDirection)` to select an appropriate sprite.

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


# Question
Title: Game development with D programming language
I have recently found out about D programming language and its basic features. It seems D is quite powerful alternative for C++ and more effective at some points. Also D can interface to C, but interfacing to C++ is limited.

The only engine I found out is D Game Engine, but it is in an early pre-alpha state and I'm not sure it's developing anymore.

Are there any 3D, physics or game engines written in D or at least wrappers for engines in other languages? Is it possible to use with D such engines like irrlicht, Ogre3d or Torque 3D without almost complete rewriting it?

# Answer
\[Edit 22 October 2014\]

I was reading that Facebook started to use D language in production environment. Even though it is still premature to say that D language will rise in the next few years it's an interesting point to mention.

> It seems D is quite powerful alternative for C++ and more effective at some points.

This is only in theory, there are multiple reasons for this:

* The designers of the language wanted this but never really achieved it, C++ is still the dominant language with longest tool chain, if you need anything (library, tool.. etc) , you probably have to figure it out yourself.
* The language compilers is not as mature as C++ compilers so keep in mind that compilers take decades to mature. What I think is that if you wrote the same exact code with the two languages (C++ and D), given it's possible, C++ will more likely be faster due to better compilers.
* I am almost certain that languages like C# will be faster (given again) you can write the same code with D, this is due to compilers being much more mature, but more important D tries to use some kind of garbage collection, garbage collectors in C#/Java are much more mature and will more likely be a better performer.
* D language was designed to make two features of C++ easier, namely, **Template meta-programming and functional programming**, if your focus is on those two maybe D will be a great a tool for writing any library that extensively use them, but again nothing is proved.
* Debuggers and tools, this is very important when using a language otherwise expect turtle speed production. C++ already have great tools so you will have to check that for D.

### My question for you would be, do you want to learn D or game programming ?

I am not saying you can't make a game engine with, but If you want to learn D, just learn D, I am sure this will enhance your programming skills.

But if you want to create an engine *and* learn D, I think this is hard, game programming is tricky on it's own, using a new programming language will make things a little bit trickier.

You will have more tasks than programming with D, communicating with other APIs and libraries, who aren't written in D. You also need to build wrappers for OpenGL, and DirectX will be even harder because it's C++. And other libraries that I don't know about like image libraries, math, sound libraries etc, you may want to write some libraries on your own.

> Is there any game/3D engines written in D or at least wrappers for engines in other languages?

As far as I know, No.

> D can interface to C, but interfacing to C++ is limited. Will it be possible to use with D such engines like irrlicht/Ogre3d/Torque 3D and how difficult?

Every language I know of, can interface with C somehow, C has a universal ABI (Application Binary Interface), C++ on the other hand doesn't, which make things a little bit more complicated.

What usually happen to communicate with C++ is to wrap the C++ engine with C interface, which is not going to be fun and cool when it comes to engines like Ogre and you are on your own. Communities are the ones who usually build wrappers so maybe you will be the first?

### So what about physics engines ?

Everything I said applies for physics engines, with a point to keep in mind **and this is only my opinion**, game engines can be written in a managed language and I know some because they use a lot of hardware acceleration, physics engines on the other hand, *mostly* use the CPU, I know some don't, but am talking about the small physics engine they are written in languages where every instruction is taken into account. Doing so with a managed language can make things trickier especially in numerical analysis and tight loop calculates (there are a lot of them in physics engine). What I mean is that garbage collection is more likely to affect your physics engine's performance more than your game engine.
> 2 votes

---
Tags: d
---


# Question
Title: Changing the rendering resolution while maintaining the design layout
I would like to increase the FPS of my project.

Currently I would like to try reducing the resolution at which the scenes are rendered.

Let's say I never want to draw more than 1280\*720. What ever the real resolution is. How should I proceed?

I tried `pEGLView->setFrameSize(1280, 720);` but only reduces the displayed size of the frame on screen (boxing).

In my activity I tried setting the size of the "surface" but this seems to completely break the layout (as defined by `setDesignResolutionSize`).

```
@Override
public Cocos2dxGLSurfaceView onCreateView() {
    Cocos2dxGLSurfaceView surfaceView = new Cocos2dxGLSurfaceView(this);
    surfaceView.getHolder().setFixedSize(1280, 720);
    return surfaceView;
}

```

Is there a way to simply set the scene resolution and display the result full screen?

# Answer
> 4 votes
Currently I draw into a texture (1280, 720) or adapted to the screen ratio. Then this texture is displayed upscaled.

# Answer
> 1 votes
My games had a "target resolution", say 1024x768. They were rendered to a texture. The video mode was set to the native resolution of the monitor, the texture would be scaled up so that it took the whole height of the mode (or width, but it's a less common case), and then drawn as a single quad. This made the game logic resolution-independent, and also did letterboxing in widescreen monitors as a bonus.

I did the same thing recently for retina- and non-retina iPads. Letterboxing is again useful with the iPhone 5.

# Answer
> 1 votes
on IOS as far as i know you can't create a framebuffer with a different resolution than the screen so the only approach is to render everything into a texture and draw it afterwards on the screen. Also targeting different resolutions is quite hard and there are a couple of things to take into accound:

Aspect ratio of the screen:

The texture you create should have the same aspect ratio as the screen otherwise thing will look stretched afterwards. If you don't want to do this you can fake the aspect ratio of the game from the projection matrix but in this case the pixels from your texture will be stretched unevenly creating aliasing artifacts that will just look bad.

Aspect ratio again:

It is important that the projection matrix takes into the account the screen also because on a wider screen you will see more on width so the projection has to be wider otherwise the content will look differently.

Menus:

This is a really hard topic but the general approach is to have the elements scaled evenly on width and height but this is not possible if you have different aspect ratios unless you split the menus into parts and apply uneven scale only on salable elements(like the empty space between buttons). Much like how html pages are made , you have the content that is fixed(or scaled evenly) and the borders are stretched until it fill the whole screen.

Artifacts generated by scaling:

When rendering to a texture and scaling it up you will get aliasing artifacts and they are hard to remove. You can use an upscale filter, but this can be expensive on mobile devices.

---
Tags: cocos2d-x, resolution
---


title: Add a "fake" Loading Screen

text:
# Question
Title: Add a "fake" Loading Screen
I'm working on a 2D game for WPF8 using XNA 4.0.

Everything goes great, but it's too fast. I was just wondering, what could I do between the end of the game and the score screen, and before the game starts? I'm looking for a sample of how to do that (black screen with "loading" write in windows phone style) or a way to implement it.

# Answer
> 3 votes
No code from me, since I'm not that experienced with XNA, but this is more a general "issue":

* First of all - as mentioned in the comments - **do not** (never ever!) add fake loading screens! People will think it's really that ressource heavy which can show your app in a worse light than it actually should be. Especially on mobile you don't usually trust an app showing constant loading screens to safe battery for example.
* Instead, add a transition. A very easy to do transition would be blending to/from black. You can do more interesting stuff when using shaders and render to texture, but this one should be more than sufficient to slow down pace a bit.

The basic steps are pretty much self-explanatory and there are multiple ways to approach this, also depending a bit on how you handle your game state, progress, etc.

* Rather than switching game state immediately, e.g. from `GAME_PLAYING` to `GAME_HIGHSCORE`, you'd set some counter. Let's call it `blending_time`.
* From there on, as long as `blending_time` isn't equal to zero, you'll just draw a black quad over the whole screen, using an alpha value based on the time left.
* Once your counter reaches zero, you do'd the state switch.
* To get a soft blending in, you could then reverse the whole thing.
* Again set `blending_time` to the time you'd like to blend (you might want to use a different value or some toggle to identify whether blending to or from black).
* As long as `blending_time` isn't 0, you'd draw once again a black quad over the whole scene with its alpha depending on the time left (this time starting with 100% opaque).

# Answer
> 1 votes
If you are looking for a smooth image transition, there is a cool and extremely-easy-to-implement shader that was used in Incredipede. In this GDC 2013 talk the art team explain it in detail. I have also implemented it in Unity. If you want to see the code to get the idea and translate it to XNA, there it is:

```
Shader "Custom/InkPress"
{
    Properties
    {
            _MainTex ("Base (RGB)", 2D) = "white" {}
            _BlurTex ("Base (RGB)", 2D) = "white" {}
    }
    SubShader
    {
            Pass
            {
                    //Usual post processing setup
                    ZTest Always Cull Off ZWrite Off
                      Fog { Mode off }

                    CGPROGRAM
                    #pragma vertex vert
                    #pragma fragment frag
                    #pragma target 2.0

                    #include "UnityCG.cginc"

                    struct v2f {
                            float4 pos : POSITION;
                            float2 uv : TEXCOORD0;
                    };

                    v2f vert (appdata_img v)
                    {
                        v2f o;
                            o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                            o.uv = v.texcoord.xy;
                            return o;
                    }

                    sampler2D _MainTex;
                    sampler2D _BlurTex;
                    float _threshold;

                    float4 frag( v2f v ) : COLOR
                    {
                        // Step 1: Get the brightness of the blur texture
                        float2 vUv = v.uv;
                        float4 returnColour = float4(1.0 , 1.0 , 1.0 , 1.0);
                        float3 texColour = tex2D(_BlurTex , v.uv).xyz;
                        float bright = (texColour.r + texColour.g + texColour.b) / 3.0;

                        //Step 2: Return the main texture pixel colour if its brightness is bellow
                        //the threshold. Clear the pixel otherwise.
                        if(bright < _threshold)
                        {
                                returnColour = tex2D(_MainTex , v.uv);
                        }

                        return returnColour;
                    }
                    ENDCG
            }
    }
    FallBack "Diffuse"
}

```

The shader above is just the transition. To achieve a better effect you should blur the image before as stated in the talk. I have omitted the blur part for the sake of simplicity.

If you want more detail and the full source, you can check my page.

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


title: Write my own level editor, questions

text:
# Question
Title: Write my own level editor, questions
I just finished to code the most important parts of my game engine (not a tile-map one), such as lights, shadows, objects update/draw, input, ecc. Now I'm making a level editor to simplify the creation of levels. I have a form that does only simple things: place the player, place a block, choose a background, place an enemy... These two components are divided between them (sorry for my bad english).

My question relies on the relation between the form (level editor) and the game engine (the game itself)

These are my thoughts:

---

For a better explaination, take this example:

* My game\_engine project holds a Light class, a Player class, a Background class, an Enemy class. My engine (**in abstract**) is like this:

```
namespace game_engine
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        enum GameStates { TitleScreen, Playing, PlayerDead, GameOver };
        GameStates gameState = GameStates.Playing;

        Enemy zombie1;
        Enemy zombie2;
        Light sun;
        Light lamp1;
        Player player;
        Background mountains;
    }

     public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        this.graphics.PreferredBackBufferWidth = 800;
        this.graphics.PreferredBackBufferHeight = 600;
        this.graphics.ApplyChanges();

        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);

        Camera.ViewPortWidth = 800;
        Camera.ViewPortHeight = 600;
        Camera.Position = new Vector2(0, 0);

        mountains = new Background(...);
        zombie1 = new Enemy(...);
        zombie2 = new Enemy(...);
        sun = new Light(...);
        lamp1 = new Light(...);

        enemy_manager.Add(zombie1);
        enemy_manager.Add(zombie2);
        light_manager.Add(sun);
        light_manager.Add(lamp1);
    }

     protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            switch (gameState)
            {
                case GameStates.TitleScreen:
                    //Something
                    break;
                case GameStates.Playing:
                    enemy_manager.Update(gameTime);
                    light_manager.Update(gameTime);
                    mountains.Update(gameTime);
                    player.Update(gameTime);
                    break;
                case GameStates.PlayerDead:
                    //Something
                    break;
                case GameStates.GameOver:
                    //Something
                    break;
            }

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            switch (gameState)
            {
                case GameStates.TitleScreen:
                    //Something
                    break;
                case GameStates.Playing:
                    enemy_manager.Draw(spriteBatch);
                    light_manager.Draw(spriteBatch);
                    mountains.Draw(spriteBatch);
                    player.Draw(spriteBatch);
                    break;
                case GameStates.PlayerDead:
                    //Something
                    break;
                case GameStates.GameOver:
                    //Something
                    break;
            }

            base.Draw(gameTime);
        }

```

---

Then I have another project which is a **form** (Level editor) with some function/tool to help me out not putting manually every entity (enemy, light, ecc ...) when initializing the game:

At this point I have to "link" the form and my game engine. To make my tests I just did copy and paste game engine code into form project. But this is the wrong idea, because I want my code to be written once. Here there are my doubts: is it possible to create a link between them, considering that:

* Inside the form there is a PictureBox where I want to render my game for full (With lights, shadows, etc)
* I want to write once the game engine so that if I modify something for example inside "Enemy" class, when editing both Level editor and Game itself would run the new code

I miss that logical link between my two entities, I need some hint to go on, something to think about in order to clear things up. I put some code, please give me some code.

# Answer
I would recommend you to take a look at the model-view-controller concept.

The **model** would be your map with all the objects on it.

The **view** would be your graphic engine which visualizes the current state of the model.

The **controllers** are the parts of the code which implement the game logic or the map editing capabilities.

When your application is in "play mode", the game mechanic controllers would be active. They would cause the objects in your game to behave according to the game rules and manage the user input as commands for the game objects they control.

When your application is in "edit mode", the game mechanic controllers would be inactive. The input controller for the edit mode would interprete the user input as commands to change the model directly.

Your visualization in edit-mode and play-mode will likely also have some difference. The play-mode view might show some HUD information about the game-state (like how much life the player has left), while the edit-mode view shows some help-lines, additional menus and so on and will likely also visualize certain objects which are invisible in play-mode. But the general rendering-engine would likely be the same. When you work object-oriented I would write an abstract base-class `GraphicEngine` which implements the general rendering engine with two extending classes `GameGraphicEngine` and `EditorGraphicEngine` which implement the game-specific or editor-specific graphic engine features.

When you do this well, you might be able to implement seamless switching between play-mode and edit-mode at any time. This would provide you with a very powerful test-tool.
> 1 votes

---
Tags: xna, c#, map-editor, windows-forms
---


# Question
Title: Should I consider a graduate degree in game development?
I am sure you guys can definitely help. Some universities, like NCSU, USC, UCSC for their master's, offer courses based on gaming and game development (some call it MS in Computer Science with an emphasis on game development). I am very interested in this field and I want to give it a shot. But since a master's degree is very costly I have to factor in the future prospects as well. I want to know if this a proper course when a career is also taken into account. Any opinions or ideas? Anyone who has followed this career line?

# Answer
> 6 votes
I agree completely with mrbinary's answer. I am a student at UNC Charlotte and we have a Game Design and Development concentration with our Computer Science degree (in the Bachelor's and Masters track). Essentially you take four classes: Intro to Game Design and Development, Advanced Game Design and Development, Game Studio (a semester long project class), and an elective class pertaining to something related to games (AI, Games with a Purpose, 3D Graphics, etc.). I also work in a research lab for the University run by the professors that created the Game Design and Development concentration doing research and development of Games with a Purpose. I have many friends who have gone through the program, and I completed it halfway through.

Long story short, everyone I know that has completed the program (some bachelors, some masters) and graduated, then sought out a job in the gaming industry, have failed to get a job. Due to my research work, I have travelled to many game related conferences to present work and see other work in the field, and this discussion has come up a lot. One cool thing about these conferences is that people from industry will attend, as well as academics. What I've heard from many people in industry (and this is backed up by none of my friends who went through our degree program getting jobs in the gaming industry) is that going through a Game Development program may actually hinder your ability to get a job in the gaming industry. This is because the games industry is so diverse in terms of how they develop games. Some companies may use C++ as their language of choice, but use it within a custom engine or a custom framework. Others might use C#, others a scripting language (Lua, ActionScript, etc.), others may focus solely on mobile development and use Objective-C or Java, others may build flash games. The choice of programming languages and development environments are extremely diverse. The problem with Game programs at Universities is it gets you experience in one specific framework and methodology of game development that may not always translate to a game companies needs.

Our program used to teach XNA and C# (which limited us to Windows and XBOX only games), and has now moved into using Unity and JavaScript, as well as WebGL with HTML5. The reason for the transition was that learning XNA and C# for 2 years was getting the graduates nowhere. The game industry has transitioned greatly in the last few years away from consoles to mobile devices and web games, so our curriculum was changed to accommodate for that. It is yet to be seen if this helps our graduates find jobs or not. From my circumstantial observations, plus what I've heard from discussions with people from industry, a Games concentration may not be beneficial when trying to get a job in industry. Of course, if you want to becomes a Games professor, then it's probably just fine! A regular Computer Science degree and some of your own portfolio projects will get you further than a degree focused on games, in my opinion.

# Answer
> 18 votes
I personally think it's better not to specialize in game development for your studies. At least over here in Europe, a "normal" computer science degree gets you as far as any game development-related degree - if not further. Programming is programming, if it's for games or not. By all means, take the game-related classes at your university and (this is the important part) pursue game development as your hobby. Get some hobby projects to the point where you can show them off during interviews when you are done studying.

Are you completely sure that you want to develop games for the rest of your working life? With a game-centered degree you might have a hard time finding other jobs. On the other hand, with a "normal" degree you have the whole range of all computer science-related jobs open to you.

I have studied "normal" computer science myself and haven't had any problems yet getting a job in the games industry.

# Answer
> 8 votes
Having graduated from DigiPen, I would not recommend attempting to specialize your educational as early as your undergraduate work (I also went to a "regular" school to work towards a "regular" computer science degree prior to DigiPen). The proper place for specialization is at the graduate level, either by attending a masters or doctorate program somewhere or studying on your own -- and this seems to be what your question is about.

If you are looking for a job in the game development industry, a graduate degree probably won't help you much. It certainly will not automatically translate into a higher starting salary or a more-senior initial job offer. If anything, you may run the risk of being considered overqualified for the entry-level positions you'd be vying for.

If you study graphics or physics, there may be a place for you in some studios that want to push the boundaries in those fields, but that's kind of a gamble; such positions would be highly competitive and there will also be plenty of industry veterans looking at them.

If you are interested in the study of the industry, or want to teach or do research, a graduate degree can be useful (and indeed, is often a requirement). But if you just want a career making games, I wouldn't recommend it.

# Answer
> 1 votes
Lots of answers here, but I want to chime in with my personal experience.

I'm in the grad program at DePaul University in Chicago. They have a number of degrees, but one of them is Computer Game Development.

In my personal experience, this program is spectacular and I can personally vouch for it to anyone who is considering DePaul. The main reason is that the degree is teaching game programming from a low level. It teaches the ins and outs of C++, to the point that I'm referring to the spec rather than online tutorials. It teaches OpenGL, both fixed and programmable pipeline.

The goal of the program is to make you an excellent problem solver in the framework of video games. The people who leave this school can dig into call stacks, disassembly, and really get down into the nitty gritty.

I would be hesitant to recommend anyone get a game degree that does not teach low level programming like this. On the other hand, I think anyone who wants to get into the game industry would do extremely well for themselves if they looked for any kind of computer science degree that digs into low level stuff like that.

When you go to apply to game programs, showing an incredible knowledge of C++, and how the code you write in it translates into assembly, will really impress them. They're looking for engineers and problem solvers, not just people who have a degree that says 'Game Programming' on it.

# Answer
> 0 votes
I recently (end of 2010) graduated as a Bachelor of Games and Interactive Entertainment, Software Engineering major with a GPA over 6.5 (highest possible GPA is 7.0). My degree is not worth the paper it's printed on.

You're better off taking a vanilla software engineering degree, and taking the game-related units as your elective. (All of this is assuming you're looking at the programming side. If not, same advice applies to art and sound design).

# Answer
> 0 votes
I have received a bachelor degree in a game development course in July and I'm already working for 2-3 months in the game industry.

Maybe it's different in the USA but over here in Europe, if you know decent C++ / C# skills and know how to work with various engines, then this adds a lot of value to your skill set.

I'm not saying it's common that this happens, but it does happen.

I do believe that programmers have an easier time finding a job if you compare it to artists (except if they are really good).

---
Tags: game-industry, education
---


# Question
Title: Cocos2d: Moving background on update: offsett issue
working with Objective C, iOS and Cocos2d I am developing a vertical scrolling shooter game for iPhone (retina display models with 640 width x 960 height pixel resolution).

My basic algorithm works as following:

* I create two instances of an image that has exactly 640 width x 960 height pixel of resolution, which we will call imageA and imageB
* I then set the two imags with exactly 480.0f of offset from each other, as the screenSize of a CCScene is set by default to 480.0f.
* At each update method call I move the two images by the same value. I make sure that their offsett stays to 480.0f

However when running the game I see a 1 pixel height line between the two images. This literally bugs me and would like to adjust this.

What am I doing wrong?

This is a zoom in on the background when the "offsett line" is visible. The white line you can see divides the two background images and is not meant to exist as both images are completely black :):

If I change the yPositionOfSecondElement value to 479.0f until the first loop the two images overlap correctly, but as soon as the loop starts the two images starts having an offsett of -1.0f.

Here is the initialization code:

```
-(void) init
{

//...

screenHeight = 480.0f;
yPositionOfSecondElement= screenHeight;//I tried subtracting an offsett of -1 but eventually the image would go wrong again
yPositionOfFirstElement = 0.0f;

 loopedBackgroundImageInstanceA = [BackgroundLoopedImage loopImageForLevel:levelName];
            loopedBackgroundImageInstanceA.anchorPoint = CGPointMake(0.5f, 0.0f);
            loopedBackgroundImageInstanceA.position = CGPointMake(160.0f, yPositionOfFirstElement);
            [node addChild:loopedBackgroundImageInstanceA z:zLevelBackground];

            //loopedBackgroundImageInstanceA.color= ccRED;

            loopedBackgroundImageInstanceB = [BackgroundLoopedImage loopImageForLevel:levelName];
            loopedBackgroundImageInstanceB.anchorPoint = CGPointMake(0.5f, 0.0f);
            loopedBackgroundImageInstanceB.position = CGPointMake(160.0f, yPositionOfSecondElement);
            [node addChild:loopedBackgroundImageInstanceB z:zLevelBackground];

  //....
}

```

And here is the move code called at each update:

```
-(void) moveBackgroundSprites:(BackgroundLoopedImage*)imageA  :(BackgroundLoopedImage*)imageB :(ccTime)delta
{
    isEligibleToMove=false;

    //This is done to avoid rounding errors
    float yStep = delta * [GameController sharedGameController].currentBackgroundSpeed;

    NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", yStep];
    yStep = atof([formattedNumber UTF8String]);

    //First should adjust position of images
    [self adjustPosition:imageA :imageB];

    //The can get the actual image position

    CGPoint posA = imageA.position;
    CGPoint posB = imageB.position;

    //Here could verify if the checksum is equal to the required difference (should be 479.0f)
    if (![self verifyCheckSum:posA :posB]) {
        CCLOG(@"does not comply A");
    }

    //At this stage can compute the hypotetical new position
    CGPoint newPosA = CGPointMake(posA.x, posA.y - yStep);
    CGPoint newPosB = CGPointMake(posB.x, posB.y - yStep);

    // Reposition stripes when they're out of bounds
    if (newPosA.y <= -yPositionOfSecondElement)
    {
        newPosA.y = yPositionOfSecondElement;
        [imageA shuffle];
        if (timeElapsed>=endTime && hasReachedEndLevel==FALSE) {
            hasReachedEndLevel=TRUE;
            shouldMoveImageEnd=TRUE;
        }
    }
    else if (newPosB.y <= -yPositionOfSecondElement)
    {
       newPosB.y = yPositionOfSecondElement;
        [imageB shuffle];
        if (timeElapsed>=endTime && hasReachedEndLevel==FALSE) {
            hasReachedEndLevel=TRUE;
            shouldMoveImageEnd=TRUE;
        }
    }

    //Here should verify that the check sum is equal to 479.0f
    if (![self verifyCheckSum:posA :posB]) {
        CCLOG(@"does not comply B");
    }

    imageA.position = newPosA;
    imageB.position = newPosB;

    //Here could verify that the check sum is equal to 479.0f
    if (![self verifyCheckSum:posA :posB]) {
        CCLOG(@"does not comply C");
    }

    isEligibleToMove=true;
}

-(BOOL) verifyCheckSum:(CGPoint)posA :(CGPoint)posB
{
    BOOL comply = false;
    float sum = 0.0f;

    if (posA.y > posB.y) {
        sum = posA.y - posB.y;
    }
    else if (posB.y > posA.y){
        sum = posB.y - posA.y;
    }
    else{
        return false;
    }

    if (sum!=yPositionOfSecondElement) {
        comply= false;
    }
    else{
        comply=true;
    }
    return comply;
}

```

And here is what happens on the update:

```
if(shouldMoveImageA && shouldMoveImageB)
    {
        if (isEligibleToMove) {
            [self moveBackgroundSprites:loopedBackgroundImageInstanceA :loopedBackgroundImageInstanceB :delta];
        }

```

Forget about shouldMoveImageA and shouldMoveImageB, this is just for when the background reaches the end of level, this works.

# Answer
> 1 votes
Don't know if this will help but here is the code for a game where we have moving clouds in the background. Is very old but will get you an idea.

```
-(id) init{
    if( (self=[super init] )) {
        first = [CCSprite spriteWithFile:@"clouds_1.png"];
        firstWidth = first.contentSize.width;
        height = first.contentSize.height;
        second = [CCSprite spriteWithFile:@"clouds_2.png"];
        secondWidth = second.contentSize.width;
        Yvalue = GO_CLOUDS_YVALUE;
        duration = GO_CLOUDS_DURATION;
        CGSize size = [[CCDirector sharedDirector] winSize];
        firstXf = -1 * (secondWidth - size.width + firstWidth/2);
        secondXf = -1 * (firstWidth + secondWidth/2);
        firstX0 = size.width + firstWidth/2;
        secondX0 = size.width + secondWidth/2;

        moveFirstDone = [CCCallFuncN actionWithTarget:self selector:@selector(callFirstDone:)];
        moveSecondDone = [CCCallFuncN actionWithTarget:self selector:@selector(callSecondDone:)];

        first.position = ccp(firstX0 + -1*firstX0,Yvalue);
        second.position = ccp(secondX0,Yvalue);
        [self addChild:first];
        [self addChild:second];
        [first runAction:[CCSequence actions:[CCMoveTo actionWithDuration:duration position:ccp(firstXf,Yvalue)],moveFirstDone,nil]];
        [second runAction:[CCSequence actions:[CCMoveTo actionWithDuration:duration*2 position:ccp(secondXf,Yvalue)],moveSecondDone,nil]];
    }
    return self;
}

-(void)callSecondDone:(id)sender{
    second.position = ccp(secondX0,Yvalue);
    [second runAction:[CCSequence actions:[CCMoveTo actionWithDuration:duration*2 position:ccp(secondXf,Yvalue)],moveSecondDone,nil]];
}

-(void)callFirstDone:(id)sender{
    first.position = ccp(firstX0,Yvalue);
    [first runAction:[CCSequence actions:[CCMoveTo actionWithDuration:duration*2 position:ccp(firstXf,Yvalue)],moveFirstDone,nil]];
}

```

# Answer
> 1 votes
It looks like your image has an anti aliasing at it's border. You can either fix this in photoshop or you could use a program like texturepacker that will extend your picture a pixel and remove this border.

---
Tags: ios, cocos2d-iphone, game-loop, image
---


# Question
Title: UV mapping issues while loading collada model exported with Sketchup
I load collada models, exported via Google Sketchup, into my Three.js (v63) scene with the Three.js collada loader.

The models are loaded, but with some, textures aren't well mapped, like in the following picture :

My first question is how to detect this kind of problems and then, is there a way to leverage the exported UVs from sketchup to correctly map the textures ?

The model from the sceenshot comes from : http://sketchup.google.com/3dwarehouse/details?mid=557d5f1b5a076bdcf53b1b21212345ca&prevstart=0

# Answer
> 1 votes
Are those textures projected? If so make unique, triangulate n-gons and then export.

3D Warehouse models typically acquire their textures from 2 sources. Google Street View and Google Earth. The textures are typical projected at the geometry so the UV coords are skewed because it is a viewed based mapping.

When you mix projection with n-gons and then export you'll typically end up with the mesh getting triangulated. This triangulation messes up the projection.

SketchUp uses unconventional mapping methods so careful texturing is needed. Triangulating in Sketchup prior to exporting is always advised.

Hopefully that will add more info to why your export looks the way is does.

There are tools available to fix such issues.

---
Tags: collada, three.js
---


# Question
Title: How or why are major video games programmed so reliably?
It seems like every five minutes, you come across yet another installer which fails to install certain components, another .NET application that throws up an unhandled or semi-unhandled error message, a web site whose links are broken or whose JavaScript doesn't work with the most recent IE, popular apps and Flash games that freeze on occasion, etc. Time and again you come across programs that, though they work most of the time, you will come across occasional serious errors with them, wherein they are either dead in the water or close to it.

I remember seeing a lot of glitches back in the NES days, but since around the early- to mid-90's, major video games seem to have been mostly free of things like this. I know there are exceptions, but basically unless you are really trying to perform some sort of hack you read about online, you just don't see any issues with them freezing, throwing unhandled exceptions, or doing anything else like that. At worst it tends to be tiny, momentary graphical anomalies that don't really matter.

In other words, major video games seem to be built to a much higher standard in reliability than most other things out there, aside from development software, despite the fact that they tend to be very large and complex pieces of software - often written in C++, no less. You just do not have the same sorts of problems with them that you do with software in other fields.

Why? How? I know this could just be a result of quality control, plus just using programmers who were at the top of their class, but I've grown doubtful of this. To me, it seems like even these measures would not ensure consistently more reliable software in situations in which it should be much less reliable. Are people really just doing their jobs that much better, or is there something more to the picture here (such as a business practice or a development technique that these companies tend to employ)?

I know that this isn't the most scientific question out there, but I still want to make sure I'm not just missing something. Thanks.

# Answer
If console only, you have far less hardware related issues, since your pool of supported devices is minimal. With a PC, every last component can be made by someone else. So the list of potential compatibility issues is near endless. The newer Windows platforms have tried to standardize drivers a bit, but that doesn't really change the overall idea I'm trying to portray.

Another part is due to manpower. A AAA game has multiple programmers with the single job as fixing bugs. Now, granted, there are more hands in the pot and thus more room for minor bugs than if a small indie team is coding, but the indie team won't likely have the same amount of programming resources.

Yet another part is QA. There are some excellent Quality Assurance departments/companies out there that can find bugs for the bug programmers. An indie team isn't going to have this, beyond perhaps a beta test. And sadly, non-QA minded people are generally horrible at feedback that is useful in fixing a bug, or sometimes even finding it. I'd probably say that most non-AAA games, even ones that aren't technically considered indie, fall under poor QA availability.

And last but not least, money. The above parts are dependent on money. Small teams are less likely to have the cash to throw around to buy hardware to test with, experienced bug fixers, and quality testers. Not to mention that their actual core programming skills might be lackluster, depending on the scenario/company.

I suppose I should also mention that many AAA titles don't do a lot of innovation in their designs. I'm not really sure that prevents bugs, but it can definitely feel like the game is more polished when all aspects work in a familiar fashion.
> 5 votes

---
Tags: game-design, architecture, testing, software-engineering
---


# Question
Title: TCG - how to program cards as separate entities
So I'm planning to try making a card game (in Java) but I'm not sure what the best way to design it is. I understand the engine stuff but not how the cards should be coded an how they should interact with the engine. The scope is like so:

We have an engine that understands the flow of the game. It knows you draw at the start, play cards at some point, have a combat step, and end the turn (switching players). This much is fine, but the concern is the cards themselves.

I want to have cards be their own entities. I'm not sure if it would be better to:

a) Have each card be their own class b) Have each card be programmed as an external script (say in Python)

I want the game engine to know as little as possible about a card. When you play a card, I want the game engine to go:

You're playing a card. Do you have resources? Ask the card how much it takes, then confirm you have it. When a card has an interaction, I want it to do as much as it can. For example, if the card says draw a card, I want it to forceably tell the engine to draw a card, or better yet, hook into the game, draw a card, and then force the engine to update itself.

Extreme cases would probably provide a better description, so if there was a card that said "players do not draw at the beginning of their turn", the engine would normally automatically draw, so we'd have to stop that. I could reasonably program something where the engine would check if anything special happens before each interaction and it would see "skip draw". Even still, how would I program that? Would I write a method in the engine to skip draw and then have the card add it as a special trigger? Would I actually have the card (perhaps programmed in Python) hook into the engine and end the draw method?

What would be the best way to go about this?

# Answer
> 1 votes
It sounds like what you want is to construct some kind of high level scripting language for the game logic interactions that cards actually *perform*. I think your idea to keep this sort of logic separated from the engine itself, is laudable (obviously this also implies that you could reuse the underlying engine for different resource-based card games, which I assume is your goal). But instead of focusing on this separation of engine and game logic early on, first write the entire thing in Java, maintaining separation of different sorts of logic (engine vs game) at class and package boundaries. That means starting out by writing your high-level game logic in Java, such as methods for different known card actions, perhaps in a separate package "gamelogic". Once you have something working, I guarantee you that it will be far easier to see the development patterns involved in migrating the necessary logic to instead be driven by your (runtime parsed) scripting language.

It would not be difficult to write some kind of token / expression parser for the sorts of interactions which your cards would perform. You could write that parser in Java and have it parse text files describing each card type, then have your engine call `play()` on the card which kicks off all the pre-parsed rules. An example card might be described by:

```
burn opponent 3 //burns the opponent for 3 damage
discard opponent [1 random hand] //force opponent to discard one card at random from hand
playagain

```

You may have more complex situations where rule resolutions need to occur in very particular order (MTG comes to mind). I guess you will figure out ways to describe these situations, as you go along.

There are different levels of abstraction that can be supported in a scripting language. You need to decide where the boundaries lie / how much effort you are willing to put in, in that regard, and then proceed from there. More general = more difficult. That's why I suggest writing it all in Java first. You may well find that you wish to retain a lot of the card rules functionality at the Java level (whether part of your engine app or separate) and then simply wrap those individual rule-application methods as keywords in a very basic, "thin" scripting language of your own devising, as above.

Your concept of having cards be "their own entities" is fine, e.g. creating them as a `Card` class. The concept of a card has to exist at the engine level, yes? So that means you encapsulate it as such. Then, every card may tie into this custom scripting through some methods which they all share as part of that class. You could even create a separate class which the `Card` has a reference to, which handles interactions with scripts; this would be good OO practice.

You're quite right about skipping cards. Ultimately, whatever script-level functionality can affect the engine, has to become engine-level functionality. You may find yourself occasionally having to add in new features to the engine code this way, as you come up with new cards that change the flow of play (hopefully there won't be too many of these). You'd also need hooks for things like "player x won the game", since the engine will have no concept of what creates a win or lose condition.

**The key point** is that it is very difficult to abstract a system when you do not yet have a working system to abstract from! Get started by architecting your system to less restrictive requirements, while bearing in mind your ultimate goal of abstraction. You will make faster progress this way.

---
Tags: java, python, card-game
---


title: (XNA) 3D Model Rotation Angles

text:
# Question
Title: (XNA) 3D Model Rotation Angles
I'm currently in the process of making a 3d "semi" top down game, the camera comes in at a very high angle near 90 to show off the 3d models. I have a main character which can move in 4 axis (up, down, left right) using the arrow keys. I'm trying to create a smooth rotation between each of the axis so that when you press right when the character faces up, his rotation just doesn't jump.

Rotations seem to be weird and I don't quite understand why MathHelper.ConvertToDegrees or Radians doesn't quite give me what I want. When I try to rotate the model, I am translating it back to the origin, rotating then translating back for my order of matrices.

Although what I've found is that for rotation in the Z-axis, 0f seems to be down, 1.6f seems to be right, 3.2f seems to be up and 4.8f seems to be left. So to translate smoothly what I do is say I'm facing up (3.2f) and I want to face, right: Rotation.Z \> 1.6 so, while it's greater keep subtracting 0.08f until we reach 1.6 or lower. This works well.

BUT my problem lies in since down is 0 and left is 4.8, when you're facing left and want to face down, you rotate clockwise all the way back to down instead of the logical counter-clockwise. This only happens in left to down or vice versa.

I've thought long and hard about this, down can also be expressed by 5.4f I assume but that doesn't really solve my problem. The approach for going down looks like this:

```
    else if (currentKeyState.IsKeyDown(Keys.Down))
    {
        //Rotate character to face this direction
        if (rotation.Z != 0)
        {
            if (rotation.Z < 0)
            {
                rotation.Z += 0.08f;
            }
            else if((rotation.Z > 0))
            {
                rotation.Z -= 0.08f;
            }
        }

```

Since for the left rotation, the rotation.Z value will be 4.8, then by this logic it'll going counter-clockwise. It's probably a simple solution but it has me stumped and one of my biggest problems is not moving on until a problem is fixed even if the game still works.

I've attached a picture of the axis just in case my post is nonsensical:

Look forward to any potential solutions.

# Answer
> 1 votes
Looks like you're working in radians, so...

* up = +/- pi
* left = -pi/2 = 3pi/2
* right = pi/2 = -3pi/2
* down = 0 = +/-2pi

(modulo 2pi)

To get the smallest difference between two input angles, you can use something like...

(disclaimer - this is back-of-napkin, so check it in case I flipped a sign that didn't show up in my pencil test cases)

```
// Returns the shortest angle from start to end
float AngularDelta(float startAngle, float endAngle)
{
  float delta = endAngle - startAngle;
  delta = ((((delta + pi) % 2pi) + 2pi) % 2pi) - pi
}

```

---
Tags: xna, c#, 3d, rotation
---


# Question
Title: Why should I separate objects from rendering?
**Disclamer:** I know what an entity system pattern is and I'm **not** using it.

I've read a lot about separating object and rendering. About the fact that the game logic should be independent from the underlying rendering engine. That's all fine and dandy and it makes perfect sense, but it causes a lot of other pains too:

* need for synchronization between the logic object and the rendering object (the one that keeps the state of the animation, the sprites etc)
* need to open the logic object to the public in order for the rendering object to read the actual state of the logic object (often leading the logic object to easily transform in a dumb getter and setter object)

This doesn't sound like a good solution to me. On the other hand it's very intuitive to imagine an object as its 3d (or 2d) representation and also very easy to maintain (and possibly much more encapsulated as well).

Is there a way to maintain graphic representation and game logic coupled together (avoiding synchronization issues) but abstract away the rendering engine? Or is there a way to separate game logic and rendering that doesn't cause the above drawbacks?

(possibly with examples, I'm not very good at understanding abstract talks)

# Answer
Suppose you have a **scene** composed of a **world**, a **player**, and a **boss.** Oh, and this is a third person game, so you also have a **camera**.

So your scene looks like this:

```
class Scene {
    World* world
    Player* player
    Enemy* boss
    Camera* camera
}

```

(At least, that's the basic *data*. How you contain the data, is up to you.)

You only want to update and render the scene when you are playing the game, not when paused, or in the main menu... so you attach it to the game state!

```
State* gameState = new State();
gameState->addScene(scene);

```

Now your game state has a scene. Next, you want to run the logic on the scene, and render the scene. For the logic, you just run an update function.

```
State::update(double delta) {
    scene->update(delta);
}

```

That way you can keep all the game logic in the `Scene` class. And just for the sake of reference, an entity component system might do it like this instead:

```
State::update(double delta) {
    physicsSystem->applyPhysics(scene);
}

```

Anyways, you've now managed to update your scene. Now you want to display it! For which we do something similar to the above:

```
State::render() {
    renderSystem->render(scene);
}

```

There you go. The renderSystem reads the information from the scene, and displays the appropriate image. Simplified, the method for rendering the scene might look like this:

```
RenderSystem::renderScene(Scene* scene) {
    Camera* camera = scene->camera;
    lookAt(camera); // Set up the appropriate viewing matrices based on
                    // the camera location and direction

    renderHeightmap(scene->getWorld()->getHeightMap()); // Just as an example, you might
                                                        // use a height map as your world
                                                        // representation.
    renderModel(scene->getPlayer()->getType()); // getType() will return, for example "orc"
                                                // or "human"

    renderModel(scene->getBoss()->getType());
}

```

Really simplified, you'd still need to, for example, apply a rotation and translation based on where your player is and where he's looking. (My example is a 3D game, if you go with 2D, it'll be a walk in the park).

I hope this is what you were looking for? As you can hopefully recollect from the above, the render system **doesn't care about the game's logic**. It only uses the scene's current state to render, i.e. it pulls the necessary information from it, in order to render. And the game logic? It doesn't care what the renderer does. Heck, it doesn't care if it's displayed at all!

And you don't need to attach rendering information to the scene either. It should be enough that the renderer knows it needs to render an orc. You'll have loaded an orc model already, which the renderer then knows to display.

This should satisfy your requirements. The graphic representation and logic **are coupled**, because they both use the same data. **Yet they are separate**, because neither relies on the other!

EDIT: And just to answer *why* one would do it like this? Because it's easier is the simplest reason. You don't need to think about "such and such happened, I should now update the graphics". Instead you make stuff happen, and each frame the game looks at what's currently happening, and interprets it in some way, giving you an on-screen result.
> 13 votes

# Answer
Your title asks a different question than your body content. In the title, you ask why logic and rendering should be separated, but in the body you ask for implementations of logic/graphics/rendering systems.

The second question has been addressed previously, so I will focus on the first question.

Reasons for separating logic and rendering:

1. The widely held notion that objects should do one thing
2. What if you want to go from 2D to 3D? What if you decide to change from one rendering system to another in the middle of the project? You don't want to crawl through all your code and make huge changes in the middle of your game logic.
3. You would likely have reason to repeat sections of code, which is generally regarded as a bad idea.
4. You can build systems to control potentially huge swaths of rendering or logic without individually communicating with small pieces.
5. What if you want to assign a gem to a player but the system is slowed down by how many facets the gem has? If you have abstracted your rendering system well enough you can update it at different rates to account for expensive rendering operations.
6. It allows you to think about things that really matter to what you are doing. Why wind your brain around matrix transforms and sprite offsets and screen coordinates when all you want to do is implement a double-jump mechanic, draw a card, or equip a sword? You don't want the sprite representing your equipped sword rendering in bright pink just because you wanted to move it from your right hand to your left.

In an OOP setting instantiating new objects has a cost, but in my experience the cost to system resources is a small price to pay for the ability to think about and implement the specific things that I need to get done.
> 7 votes

# Answer
This answer is only to build intuition of why separating rendering and logic is important, rather than directly suggesting practical examples.

**Let's assume we have a big one elephant**, nobody in the room can see the whole elephant. maybe everybody even disagrees on what it actually is. Because everyone sees a different part of the elephant and can only deal with that part. But in the end this doesn't change the fact that it is a big one elephant.

The elephant represents the game object with all its details. But nobody actually needs to know everything about the elephant (game object) to be able to do its functionality.

Coupling the game logic and the rendering is actually like making everyone see the whole elephant. If something changed everybody needs to know about it. While in most cases they only need to see the part that they are only interested in. If something changed the person who knows about it, needs only to tell the other person about the result of that change, that is what only is important to him (think of this as communication via messages or interfaces).

The points you mentioned are not draw backs, they are only draw backs if there was more dependencies than there should be in the engine, in other words, systems see parts of the elephant more than they should have. And this means the engine was not "correctly" designed.

You only need synchronization with it's formal definition if you are using a multi-threaded engine where it puts the logic and the rendering in two different threads, and even an engine that needs a lot of synchronization between systems is not particularly greatly designed.

Otherwise, the natural way to deal with such case, is designing the system as input/output. The update does the logic and outputs the result. The rendering is only feed with the results from the update. You don't really need to expose everything. You only expose an Interface that communicates between the two stages. The communication between different parts of the engine should be via abstractions (interfaces) and/or messages. No internal logic or states should be exposed.

Let's take a simple scene graph example to explain the idea.

Updating is usually done via a single loop called the game loop (or possibly via multiple game loops, each running in a separate thread ). Once the loop updated ever game object. It only needs to tell via messaging or interfaces that objects 1 and 2 where updated and feed it with the final transform.

The rendering system *only* takes the final transform and doesn't know what actually changed about the object (for example specific collision happened etc). Now in order to render that object it only needs the ID of that object and the final transform. After that the renderer will feed the rendering api with the mesh and the final transform without knowing anything else.
> 6 votes

---
Tags: game-design, rendering, logic
---


# Question
Title: How can I get my Flash game to scale to all mobile device screen sizes?
I want my application to automatically scale its size depending on the screen size. I want my application to fit any screen size automatically. I am making my application for mobile devices, how can I do this? I am fairly new at flash so please make it a bit simple!

# Answer
> 1 votes
Use a framework like Starling that supports this out-of-box.

---
Tags: android, flash, actionscript-3
---


title: When to use class/objects for graphics

text:
# Question
Title: When to use class/objects for graphics
I am fairly new to game development, but I have a good programming background with object oriented programming.

But with games, I do not know when I should use an object (or class) for an entity on the screen or whether I should just draw the images straight to the screen.

I *think* that for any graphic objects that need interacting with (say the player or certain environment objects) would need their own class and just decoration (the image that make up the background) could be drawn straight to the screen.

So, my question is: when do I use an object or class for my graphics?

If it makes any difference, I am using LibGDX.

# Answer
It does often depend on what kind of interface the library/language provides and what kind of game it is there is no real right answer. If for example you have a 2D game using a tilemap, I prefer using some form of class/structure to keep the properties together, but if the background lacks properties that might be used to handle say collision it can as you say just be drawn to the screen as in LibGDX you can store the X and Y coordinate in the Sprite class which will be ultimately used to draw any decoration images which you could store in a collection.

Generally as long as you don't go crazy with inheritance classes will not create much of an overhead if you prefer thinking about things as objects it will probably make it easier for you to make your game.
> 0 votes

---
Tags: 2d, game-design, software-engineering, libgdx, objects
---


# Question
Title: How can I create a tile set that will allow me to render a soccer pitch in perspective?
I am making a soccer game that needs a large pitch image (the whole play field area is about 3300 * 1200 pixels).

I know I should use the Tiled map editor to create a tile map so that I can create the whole soccer pitch by using just a few tiles, but I'm not sure how I can create a tile set that will allow me to create good-looking fields like in these games:

As you can see, the soccer pitch is not a rectangle but more of a trapezoid, so it changes the way we draw border and grass stripes. The grass stripes are sloping, and the slope changes the closer they are to the goal. That makes it very hard to replicate in a limited amount of tiles.

Currently, I have 3 layers for my field. Each tile is 64 * 64 in size, and I create them this way:

1. The border tiles. Since the border is not repeating, I take the border, cut it up into tiles, and add them to the tile set. It's fussy, but it seems this is the only way.
2. Light colored grass. I have a single, repeating 64 * 64 tile that is used to cover the base layer of the field.
3. Deep colored, sloping stripe grass. This is the one I can't figure out how to create.

How can I create that last set of tiles or otherwise achieve my effect?

# Answer
> 2 votes
I would recommend you to have just one, unshaded grass texture and create the bright and dark stripes procedurally by making the texture brighter or darker.

# Answer
> 1 votes
I'm not sure tiles are necessarily the way you'd want to approach this ideally. I think a better fashion would be to use non-tile-aligned sprites, or some other method such as rendering the base field as a single textured polygon and rendering the "stripes" as alpha-blended polygons on top of it.

That said, I can see a way you could potentially organize your dark grass tiles, based on the information and screenshots you provided:

Each strip of dark grass is oriented at some fixed angle from vertical. The middle strip might be completely vertical, the next stripe ten degrees off, the next twenty degrees, and so on. You can evenly fit into a tile set any angle that will completely bisect a column of *N* tiles from one corner to another. For example, here are three tiles that might be used:

The left image is a single 64x64 tile, and the right is two tiles stacked on top of each other to allow for a different stripe angle. Similarly, you could use three tiles, or four, and so on.

You will need a set of tiles for each edge angle. You will be able to mirror the tiles horizontally around the center stripe, and rotate them to handle both borders of an edge. Finally, you may need a single solid dark grass tile as well.

This approach is fairly limiting, however, because the size of the tiles will determine how many angles you have available to you, and how wide your stripes must be (which may result in non-uniform stripe widths).

You can alleviate the problems somewhat if you build your game so that you don't have to actually align tiles to a fixed grid, because you can tile the stripes "off the grid" and use only one tile per edge angle. At that point, however, you are already well on your way to my (and everybody else's) suggestion of not bothering to constrain yourself to a tile set anyway, and so you might as well go all out.

# Answer
> 0 votes
I think you might need to do quite a lot of work to fit the square peg of non-uniform diagonals into the round hole of a tile grid.

Will your environment/tech constraints allow you to mix-in some arbitrary textured polygons? You could build a row of simple quad stripes with a repeated texture each, or one large quad with some shader math to blend between textures. Then render the rest of your sprites on top.

Either approach will likely require significantly less texture memory than baking every possible variation in light/dark slope into a tileset, and it should give you much more flexibility to iterate and refine the look without re-generating the tileset every time you change something.

---
Tags: cocos2d, tilemap, isometric
---


# Question
Title: A number of teams playing against each other: what is a fitting game term?
Basically I am looking for the right expression for a specific set (usually 2-6) of teams (a team is a group of individuals controlled by one player) in a tounament-like game. The team-set is a subset of a larger number of existing teams e.g.: there exist 10 teams t1, ..., t10. Team-Set 1 is {t1, t3, t7}, team-Set 2 is {t1, t5, t8, t10} and so on. What would be a good expression for "team-set" in a somewhat-military (fun-based combat) game context?

The teams of the set fight against each other, and not together (alongside each other). So I am looking for a somewhat confrontative term.

# Answer
> 1 votes
How about battalion? I think it fits what you are wanting.

# Answer
> 1 votes
You could use some of the terms from Wikipedia's Military Organization page, for example:

* Formation
* Regiment
* Division

---
Tags: game-design, terminology, tournament
---


# Question
Title: How can I create a VBO when I don't yet know how many vertices it will contain?
I'm trying to convert my 3D block work rendering from immediate mode and display lists to VBOs. I'm having trouble understanding how to properly handle creating the buffers: I really don't know how many vertices, colors, and texture coordinates I'll be passing in until *after* I've already iterated all of the block faces I expect to render.

How can I create a VBO when I don't know it's size? Every single tutorial/example uses a fixed amount.

# Answer
> 5 votes
You can't. VBOs are not dynamically-resizing resources, so you have to create them with a fixed size (you can create the buffer *objects* beforehand, but you will need to fix the size of the buffer when you call `glBufferData`).

You don't really want to be creating and discarding buffer resources every frame (which is what you are implying here, because that would be one of the more direct ways to go about an immediate-mode-to-VBO transition).

You could consider instancing. Essentially here you'd be creating a single VBO to represent a cube and rendering it multiple times for every *actual* cube (using different, unique-per-cube transformation matrices). This might feel like a lot to bite off right now, though (and is not without its caveats, especially if you have multiple different textures and other effects you'd want applied to different cubes). You should keep it in the back of your mind, though.

As an intermediate step, consider a simple *batching* approach where you create *N* VBOs, each of which can hold *M* cubes:

* Create your *M* VBOs when the program starts, each with enough space to hold *M* cubes. Make sure you create them with the dynamic usage hint, since you're going to be re-writing their content every frame.
* Every frame, lock a VBO and start to fill it up with cube data as you traverse the scene. When you write enough cubes that you are at the end of the VBO, unlock it and lock the next one in your set. Repeat until you run out of cubes or you run out of VBOs.
* Render all the VBOs you filled up. Make sure that if you partially fill the last VBO (as you usually will), you account for that when submitting the VBO.

You will need to tweak the specific values of *N* and *M* experimentally, most likely. You can also handle the case where you guess low (when you run out of VBO space but still have more cubes to draw) by allocating another *M*-sized VBO *right there*, and adding it to your reusable VBO pool so you'll also use it next frame. This will probably result in a stutter that frame, but it's also probably better than just not drawing the remaining cubes.

Now, your question mentioned blocks so I'm gathering you're working on a Minecraft-like game. There are a lot of other questions on this site having to do with Minecraft-like scene representation and rendering that you might find useful:

...and so on. Some of them discuss topics above-and-beyond what you specifically asked, but they may be useful to you.

# Answer
> 2 votes
When using OpenGL, generating VBOs is just calling the function `glGenBuffer`. You don't need to know the size of the buffer until you're ready to add the data to the buffer. So what you can do is generate your buffers, then calculate the vertices you'll need (and all that other stuff). Once you've calculated the number of vertices, you can call `glBufferData` with the correct size.

Unfortunately I've only used OpenGL in C++ (using glm usually), but I believe the same concepts apply to Java as well. Here's an example of what you can do, assuming you store your vertex info in something similar to a std::vector:

```
//Generate your buffers
GLuint vboID;
GLuint uvboID;
glGenBuffers(1, &vboID);
glGenBuffers(1, &uvboID);

// Calculate your vertex info here
// We'll assume you use the following for storing your data
std::vector<glm::vec3> vertices;
std::vector<glm::vec2> uvs;

// Once you've calculated your vertex info, load it into your buffers
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * vertices.size(), &vertices[0], GL_DYNAMIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

glBindBuffer(GL_ARRAY_BUFFER, uvboID);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * uvs.size(), &uvs[0], GL_DYNAMIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);

// Draw your geometry here
glDrawArrays(GL_TRIANGLES, 0, vertices.size());

```

Of course, this is a somewhat simplified example, as I didn't include any code for setting your current active program or using a Vertex Array Object, but it illustrates the solution to the problem you're having. Note that you don't have to know how big your vertex data is until your call to glBufferData. Keep in mind there's a lot I didn't cover here (such as making sure you don't call glBufferData over and over again if your data didn't change).

Also, I'm a completely self taught programmer, so I'd appreciate it if anyone points out anything that could be done in a more efficient manner. I learned OpenGL from this site:

http://www.opengl-tutorial.org/

You may also want to check out this site as well, as it also covers OpenGL fairly well:

http://ogldev.atspace.co.uk/index.html

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


# Question
Title: Can not seem to adjust the speed of my Car
I'm programming in `C++`, rendering in `OpenGL` and using `GLM` for matrix/vector manipulation and I have implemented very (very) basic car controls; ignoring many forces that are present in reality.

Since calculating the cars position using a velocity vector, the car moves ridiculously fast and I am unable to slow it down for some reason.

I've tried adjusting the velocity before rendering the cars position but doesn't seem to affect it. (unless of course I'm overlooking something silly).

This is the keyboard input which controls the angle of rotation and movement back and forth:

```
if (FORWARD)  { globalPos -= velocity; BACKWARD = false; }
if (BACKWARD) { globalPos += velocity; FORWARD = false;  }
if (ROT_LEFT) { rotX += turningAngle;  ROT_LEFT = false; }
if (ROT_RIGHT){ rotX -= turningAngle;  ROT_RIGHT = false;}

```

This is the conversion to radians and updating the velocity:

```
rotX_rad = rotX*PI/180;
velocity.x = sin(rotX_rad);
velocity.z = cos(rotX_rad);

```

This is then adding the velocity to the current position of the car:

```
globalPos.x + velocity.x;
globalPos.z + velocity.z;

```

It turns/rotates fine at a small increment (`0.01f`) but flys forwards and backwards very fast. In an aim to make the speed (of how fast the car appears to move in terms of rerendering), I tried this with no luck; it didn't seem to even affect it:

```
globalPos.x + velocity.x/800;
globalPos.z + velocity.z/800;

```

All of the code above (except the function for keyboard input) is in the `renderCar();` function before using `GLM` to translate the `globalPos` of the car.

Is there anything I'm overlooking which controls the speed? or something I can implement to slow things down?

# Answer
> 0 votes
Assuming your velocity vector is the distance you want a car to move per second, you need to be calculating the delta time between the last update cycle and the current one. You then multiply the velocity vector by the delta. Otherwise, you're adding the full velocity vector every update.

For example, say you want a car to move forward at 100 m/s. Say you have an update cycle every 1/10th of a second (for simplicity). Currently, you'd add 100m to the car's position every update cycle, so you'd add 1000m in one second, assuming the forward key was held the entire time. What you need to do is multiply the distance by the delta, in this case 1/10 (you should be calculating this dynamically unless you have a fixed update cycle time). This way, if you hold down your forward key, you only move 100m in one second, instead of the 1000m.

If you're updating the game as fast as you can, then the example I provided would be even more extreme- if your computer runs through the update loop 500 times in a second, your car moved 50000m in that second instead of the intended 100m. Here's a code example of how you could implement what I described:

```
void update()
{
    // You'll need to have some way to get the time elapsed in milliseconds.
    // lastUpdateTime can also be in an object instead if you prefer, I'm just
    // putting it here as a static variable for simplicity
    static int lastUpdateTime = getTime();
    int currTime = getTime();

    // Make sure to use 1000.0f here! Otherwise you'll be doing an integer division
    float delta = (currTime - lastUpdateTime) / 1000.0f;

    // Check for keyboard input

    // Process the keyboard input
    if (FORWARD)
    {
        globalPos += velocity * delta;
    }

    // A mistake I often make is forgetting this line. If your car accelerates
    // over time when it shouldn't, check if you forgot this line
    lastUpdateTime = currTime;
}

```

---
Tags: c++, physics, vector, linear-algebra
---


# Question
Title: Structuring server-side networking with entity-component systems
I've been working on an online game, and recently have been working on converting the base of the game to use the Artemis Entity System Framework. I'm having a bit of difficulty conceptualizing exactly how the server networking should be changed to work with this approach.

My original approach was to have each session receive packets, attach session information to them and then push them to a master queue. I then had a seperate thread (let's call it InputHandler) which was responsible for removing packets from the master queue and processing them. During the packet handling, this thread can add packets to be sent to clients to an output queue. I then have another thread (let's call it OutputHandler) read from the output queue and dispatch the packets to the appropriate sessions (for example if a packet needs to be sent to all sessions or a single sesion).

My initial idea when converting to use Artemis was to have yet another thread (WorldProcessor) take care of doing all the entity processing (this is where AI, general logic, automatic saving, etc. would be done). However I realized that I could no longer do things such as adding entities from the InputHandler thread as it could cause concurrency issues.

Would a better idea be to do the world processing in the InputHandler thread? I thought this could maybe be done by having a Networking system which would try to handle as many packets as possible during a given time frame and then pass control to the other sytems. Another approach I considered was having the InputHandler add events to a queue in the WorldProcessor which would then process these events during the system processing, but I feel this is adding another layer of complexity and that there must be a better way.

I was hoping you could give me some insight or some tips on how to go about connecting the networking and the world processor in a thread-safe fashion.

# Answer
There is no need to separate network reading from writing. It's pretty common to have some asynchronous process that reads from sockets in a non-blocking manor and checks whether there is data to send and transmits it when there is.

In fact, my network code in C++ uses a `boost::asio::io_service` in conjunction with a thread pool of approximately 4-5 threads to handle thousands of simultaneous sessions. This code basically issues a read operation on a socket with an IO completion callback. When the read has data I can process, it calls the callback handler in one of the 4-5 threads, the data is fetched from the network buffer and if a full packet is received, the handler passes the packet off to the world processor. Additionally, this same process waits for output packets to be placed on the output queue and when data is made available, it calls the callback handler, pops a packet from the queue and sends it over the socket. When the send completes, the packet is removed from the outbound queue and if the queue isn't empty, the process repeats until it is.

The other important thing to note here is that using a single master queue comes with it's own drawbacks. If your server is quite busy, such a queue can become the bottleneck if you're allowing multiple asynchronous reads to complete for multiple sessions and you're trying to write the inbound packets to the same queue.

We allow our session class to hold both an input & output packet queue. The `io_service` takes inbound packets and places them in the input packet queue and monitors the output packet queue and transmits any packets it finds.

At this point, you could allow your world processor to iterate your sessions, process each session's input queue and add any response packets to the session's output queue. The problem this can present is what if two sessions send packets in quick succession but you process them in reverse, allowing player B to kill player A when in reality player A should have killed player B?

To resolve this, the world processor has a pre-processing step where all session packets are combined from their input queues, packets are sorted in time-receipt order and then processed. This minimizes the locking of each session's input packet queue to avoid contention on receipt of new packets, and it allows you to handle packets as if they were pushed onto a single master queue in the first place.

HTH.
> 2 votes

---
Tags: java, networking, component-based, artemis
---


# Question
Title: XNA mesh.Draw() takes the longest CPU time
We have a problem. Our game steadily slows down as we increase the number of models we draw. When the number reaches 100 - FPS is dead. Our humble tests showed that the reason is not GPU. This is what we did:

* Rendered models with the most basic shader code - nothing changed;
* Checked the NVidia NSigt metrics - GPU was less and less loaded per second as we increased number of models;

At the same time, a simple Windows Task manager showed that, as the number of models rise, the load increases (up to a 100%) on the single CPU core that our game uses. So we are pretty sure our game is running slowly because of the CPU.

We then moved on and tried to identify which line exactly causes the problem. We used c# TimeSpan metrics and timers for that. Our research showed that the biggest cause of the slow performance is... mesh.Draw() function used by every model that we draw.

We tried commenting this very line and things improved instantly (ofc. nothing was drawn on the screen).

So the question is, what are we to conclude from this? mesh.Draw is a closed function and we cannot optimize it. Trying to bruteforce parallel it is impossible (i guess it was natural). But something tells me that we need to look elswhere if this function is slowing the CPU, the question is where?

Update: here is the code I use to draw the model: public void Draw(...) { int index = 0;

```
            int i = 0;

            foreach (ModelMesh mesh in Actor.Model.Meshes)
            {

                bool isDrawable = false;
                #region Check if this ModelMesh needs to be drawn according to PartsToDraw (string) list.
                foreach (string s in PartsToDraw)
                    if (s == mesh.Name)
                        isDrawable = true;
                #endregion

                if (isDrawable)
                {
                    int effectStartIndex = index;
                    foreach (Effect effect in mesh.Effects)
                    {
                        if (Actor.MatrixPaletteParams[index] != null)
                        {
                            Actor.WorldParams[index].SetValue(World);
                            Actor.MatrixPaletteParams[index].SetValue(Actor.Palette[i]);
                        }
                        else
                            Actor.WorldParams[index].SetValue(Actor.Pose[mesh.ParentBone.Index] * World);

                        if (drawType != null && drawType.DrawShadow)
                            SetShadowEffectParameters(effect, renderer, drawType.DrawShadowMort);
                        else
                        {
                            SetCommonEffectParameters(effect, renderer);
                            SetLitEffectParameters(effect, renderer, drawType);
                        }

                        index++;
                    }
                }
                else
                    index++;

                if (isDrawable)
                    mesh.Draw();

                i++;
            }
        }

```

"Set...EfectParameters" methods mostly consist of effect.Parameters\["SomeParameter"\].SetValue() calls. I pass around 30 parameters to the GPU there, mostly floats, matrices and bools. Moreover each ModelMesh has three textures that it passes into the GPU. I have no idea how fast this works and if it can be optimized. It should be fast.

You should also note that I draw a skeletaly animated model using Dastle's XNA Animation Component library. Once again, I understand that this might be the reason behind lags, and we did find the weak spot of the animation code, but why on Earth does the metrics show that mesh.Draw is the slowest spot? What is happening there?

# Answer
> -1 votes
It's really weird that no one answered my question, but the truth is I simply hit a batch limit. Indeed Draw takes the longest time on the CPU and that is why you need to limit the number of draw calls per frame. Andrew Russell has a brilliant series of answers here about this problem: https://gamedev.stackexchange.com/a/37794/31853

---
Tags: xna, models, optimization
---