title: Registering XNA Custom Pipeline

text:
# Question
Title: Registering XNA Custom Pipeline
A while back I was looking for a way to export / load Models in XNA for animations. I took the advice from a comment, and tried using the "SkinnedModelProcessor" he linked me to. It worked great at home, but at school, I can't seem to get XNA to acknowledge that I have a custom pipeline in the solution. I've added the references to both the content project and the main project, but no luck. When I compile the example, Visual Studio complains that the content processor can't be found. When using my own project, Visual Studio doesn't have the custom Pipeline Processor as an option. When using the example, "SkinnedModelProcessor" is the value in the fields, but if I click on the combobox, that option isn't there, and VS still complains. Obviously this is a problem with how Visual Studio is configured, but I have absolutely no clue what I should do about it. Any suggestions guys? I guess I could build the code for animations at home, and not worry about it at school, but that sounds like the easy way out.

\[/walloftext\]

Some notes that are probably worth mentioning: * Any settings that I apply are reset when I log out. * Any changes to the C drive are reset when the computer shuts down. * The project is stored on a network location, which has caused problems in the past, evidently. ( Although, I personally don't know what these problems would include ).

# Answer
If anybody else has this problem, I'll point out a work-around I've discovered. The problem was that the project was stored on a network. For now, I'll just have to copy the project's files onto my desktop after I log on, and return it to my network location for saving. It's a pain, but I don't see many other alternatives here.
> 1 votes

# Answer
Taking some shots in the dark...

Some things to troubleshoot:

* Is XNA installed properly? Does a example project work on the school computer?
* Are you copying over the entire project folder? There are a lot of setting files that need to be in place for visual studios to discover and recognize your assets.
* When you create the project on the school computer, are you in fact choosing to create an XNA windows application, as apposed to a C# application or something else?
* Does Visual Studios actually recognize your network location? Is it a place you can reach with the command prompt (with the \[driver-letter\]: command, perhaps)? Visual Studios will choke if it cannot reliably find a location.

Build information is program agnostic, it should be part of your project files. If the computer gets reset every night, it should not matter as long as the project is preserved as a whole.

The only other thing I can think of is to make sure there is no directory mis-match between your home computer and school computer.
> 0 votes

---
Tags: xna, pipeline
---


# Question
Title: Which Swing control should I use to render graphics with?
I'm using the Swing UI toolkit in Java, and I want to use the `Graphics` class to draw images and grids in a control. Which is the most appropriate control for this?

# Answer
A cursory bit of searching with Google suggests that you probably want to use JPanel for this, although it's possible you could make use of any control since it looks like the technique you'll want to use is to subclass the control and override a method (the `paintComponent` method, specifically), which will give you a `Graphics` instance you can use for rendering.

JPanel appears to be a very basic empty control and so is probably the ideal choice for this.
> 3 votes

---
Tags: java, graphics, swing
---


title: mixing forward and deferred rendering

text:
# Question
Title: mixing forward and deferred rendering
Simplified version of my deferred rendering looks like this:

* bind fbo1
* clear color and depth buffers
* gbuffer stage (gbuffer contains only these pixels which pass a depth test)
* unbind fbo1
* bind fbo2
* clear color buffer
* draw a full screen quad, shading stage (render to the texture for some post processing effects)
* unbind fbo2
* clear color and depth buffers
* draw a full screen quad and render to the default framebuffer

How to combine that with the forward rendering ?

# Answer
> 3 votes
Copy the depth information to the la-buffer and then render normally to the la-buffer using forward shading. All you need to do to copy over the depth information is add this to the light accumulation fragment shader:

```
gl_FragDepth = texture(depthBuffer, texCoord).r;

```

---
Tags: opengl, deferred-rendering
---


title: Gaussian blur filter and "shimmering"

text:
# Question
Title: Gaussian blur filter and "shimmering"
I have a fairly bog-standard Gaussian blur filter (seperable) I'm using to make a glow effect in my pipeline. At the moment I'm rendering it only to 256x256 texture and then doing a very simple additive combine with the scene to get the effect.

Due to the low resolution of the blur texture, I get quite a bit of "shimmering" of the blur when the camera moves around. Actually I noticed this in the Mass Effect 2 game, where they "glow" the specular highlights and shimmering is visible there.

Does anyone know of any technique for reducing or eliminating shimmering/aliasing that doesn't involve rendering the blur to a higher resolution texture (and so killing performance)? I'm already using GL\_LINEAR in my samplers, which helps a bit, but not all that much.

Here's a little YouTube clip of the blur, although it's hard to see after YouTube have downsized and messed around with the clip, unfortunately.

Note that I read this article about real-time glow, and they briefly mention shimmering, but don't go into detail about solutions.

For completeness, I include my blur shader below.

```
#version 420

// Input uniforms.

uniform vec2 uniform_TexelSize;
uniform float uniform_BlurScale;
uniform float uniform_BlurStrength;
uniform int uniform_Orientation;
uniform int uniform_BlurAmount;

// Shared.

in vec2 attrib_Fragment_Texture;

// Samplers

uniform sampler2D Map_Diffuse;

// Result

out vec4 Out_Colour;

// Local Functions

float Gaussian (float x, float deviation)
{
    return (1.0 / sqrt(2.0 * 3.141592 * deviation)) * exp(-((x * x) / (2.0 * deviation)));
}

// Main

void main(void)
{
    float halfBlur = float(uniform_BlurAmount) * 0.5;
    float deviation = halfBlur * 0.35;

    deviation *= deviation;

    float strength = 1.0 - uniform_BlurStrength;

    vec4 colour = vec4(0.0), texColour = vec4(0.0);

    // Horizontal or vertical?

    if (uniform_Orientation == 0)
    {
    // Horizontal.

        for (int i = 0; i < 10; ++i)
        {
            if (i >= uniform_BlurAmount)
                break;

            float offset = float(i) - halfBlur;

            texColour = texture2D(Map_Diffuse, attrib_Fragment_Texture + vec2(offset * uniform_TexelSize.x * uniform_BlurScale, 0.0)) * Gaussian(offset * strength, deviation);

            colour += texColour;
        }
    }
    else
    {
        // Vertical.

        for (int i = 0; i < 10; ++i)
        {
            if (i >= uniform_BlurAmount)
                break;

            float offset = float(i) - halfBlur;

            texColour = texture2D(Map_Diffuse, attrib_Fragment_Texture + vec2(0.0, offset * uniform_TexelSize.y * uniform_BlurScale)) * Gaussian(offset * strength, deviation);

            colour += texColour;
        }
    }

    Out_Colour = colour;
}

```

# Answer
OK, I fixed the problem by implementing a different way of doing it I found here. I've made this a bit quicker by doing the set-up of the incremental Gaussian in the vertex shader and passing that into the pixel shader (no point in doing it in the pixel shader when it's not dependent on anything else).

It still shimmers, but it's no way near as bad as it was before. Not sure why (!). Also it's a bit quicker with the incremental, rather than the full evaluation per-pixel.
> 1 votes

---
Tags: shaders, glsl, blur
---


title: Game Design Schools in Canada

text:
# Question
Title: Game Design Schools in Canada
I am a High School student in Ontario and i am trying looking for college/university programs the are specifically about game design. There are quite a few at most colleges near me, but they are all BA's and I am looking for a BSc. The only one i have been able to find is at digipen but that is across the continent and more importantly outrageously expensive. Does anyone know of and programs in Canada or the US that offer a BSc in Game design?

# Answer
UOIT has a Bachelor of Information Technology in Game Development. It's a pretty new school, but I have heard nothing but good things.
> 5 votes

# Answer
I wouldn't consider Game Design a science, much like I wouldn't consider Interior Design a science. Though interior design is certainly different from game design, I think it is an appropriate parallel to make when looking at the type of degree you will get. Is there a reason you don't want a BA?

You should figure out what you mean when you say "game design". That term is used for many different areas of making a game. If you mean programming a game then you should consider getting a degree in computer science or software engineering. From a quick search on the googles I found three computer science programs with game design minors/specializations in Ontario:

All of these universities have well respected computer science programs.

If you want to do any other part of creating a game, I highly doubt you will find a Science degree for it. That being said, you don't need a degree with "game design" in it to get into the industry. You can learn game specific knowledge on your own with help from the internet or perhaps other students with similar interests. A game specific program would probably not give you a well rounded, general education, so if your plans to get into the industry don't work out, or you change your mind, you may end up with a useless degree when looking for another type of job.

EDIT: Here are some related questions about specific disciplines:
> 5 votes

# Answer
I'm not sure if this will help you , but I'm currently enrolled in the Game Level Design course at Sheridan College in Oakville. It's the sister-program to the Game Design program they have here - we study our respective fields for a year (though there's talk about making it a 2-year program) and then we collaborate and make a game during the following half-year period. The idea is that we develop skills for a year, and then apply them practically for the remaining half-year of the course, so that we have a really solid addition to our portfolios at graduation. All of my instructors have backgrounds in game development (EA, Ubisoft, Rockstar, Bioware, Silicon Knights ((before they sucked)) etc.)

It's a great program so far(Game Level Design), and we learn a lot about becoming a Level Designer... We're covering 3D modelling in Maya, Level Design in Unity and UDK, Game History, Story/Cinematic/Character development and basic programming.

The only catch is you need a BA in a related field to be accepted because it (and the Game Designer program) are post-graduate courses.

If you haven't graduated from a University/College yet, and want to be a designer, they tell us that pursuing a BS in Computer Sciences is a good idea (or anything that focuses in C+, since it seems quite common), or if programming is the anti-Christ to you (like it is for me), then a strong background in Visual Art, Literature, Architecture, etc. is a good plan.

Here are the links to the two programs:

Game Level Design at Sheridan College

Game Design at Sheridan College
> 1 votes

# Answer
If you are really looking in the US you could try to apply Northeastern University. It's a five year program but they will help you get two or three six month internships at real game companies. You could also try to look for schools in Redmond Washington. I'm not sure what schools are there but I know a few of them have exclusive deals with Nintendo to allow their students to work as play testers or help with content localization.
> 0 votes

# Answer
You should look into University of Ontario Institute of technology.
> 0 votes

---
Tags: game-design, education
---


# Question
Title: Making a physics body so that another body passes through
Basically I "think" I want a static body that does not have any density so another body can "pass through it" without getting slowed down. I tried this and it doesn't seem to work. What would be the proper way to do this?

Any version (C,C++, Java) would be fine for an answer.

# Answer
A collision filter is probably what you are looking for, since Box2D makes all objects collide by default.

Take a look at this tutorial: http://blog.allanbishop.com/box-2d-2-1a-tutorial-part-5-collision-filtering/
> 2 votes

---
Tags: box2d
---


# Question
Title: Unity's "Stats" window displays bizzare number of triangles and vertices
In my Unity scene I have:

* 7-8 Barrels (with lids) each at about 2-400 triangles.
* 4 planes, each at at the very most 200 triangles
* camera, 3 lights, a FPS controller

When I turn on the "Status" button in the lower left view port, it reports "14.1K triangles and 12.k vertices":

I've double checked everything, there's no way the elemens in the scene can amount to so many triangles. The barrels in both Blender and Unity report having the number of triangles I've specified above:

Here's a Blender screen shot:

And here's one from Unity:

I've also checked the Hierarchy panel to see if I haven't accidentally duplicated stuff which might get to be on top of stuff (such as 100 barrels all in the same position so as to look as if there's just one there), and this is not the case.

So my question is: am I misinterpreting the Unity stats window? Is it a bug in the reported triangles count there? Or am I just completely missing how all this works ?

# Answer
> 8 votes
In forward rendering each object that is affected by a light source is rendered for each light. So with two lights, you're rendering twice as many polygons than if you had a single light.

On top of that, the optimized mesh that unity generates/imports for you may not be as few polygons/verts as what you make. I think it uses triangle strips and makes a lot of degenerate triangles so that it renders faster.

See also:

http://docs.unity3d.com/Documentation/Manual/RenderingStatistics.html

> **Draw Calls** The total number of meshes drawn after batching was applied. Note that where objects are rendered multiple times (for example, objects illuminated by pixel lights), each rendering results in a separate draw call.

# Answer
> 0 votes
Triangle and vertices counted also include the plane and whatever those 2 black human figures. Unity's planes are ok, but if you wanted you could only use 2 triangles to make up the plane.

* Create a new folder in the project tab, name it "Editor" Within the editor create a boo script and name it "OptimizedPlane"
* Create a new folder in the project tab and name it "Model"

Copy and paste the follow code:

```
import UnityEngine
import UnityEditor

class OptimizedPlane (Editor):
[MenuItem('GameObject/Create Other/Optimized Plane')]

static def Init ():
    customPlane as GameObject = GameObject("Optimized Plane")
    meshFilter as MeshFilter  = customPlane.AddComponent(MeshFilter)
    customPlane.AddComponent(MeshRenderer)

    destination as string = 'Assets/Model/OptimizedPlane.asset'
    mesh as Mesh = AssetDatabase.LoadAssetAtPath(destination, Mesh)

    if not mesh:
        mesh = Mesh()
        mesh.name = 'Optimized Plane'

        vertices   as (Vector3) = (Vector3(-1,0,1), Vector3(1,0,1), Vector3(1,0,-1), Vector3(-1,0,-1))
        uv         as (Vector2) = (Vector2(-1,1), Vector2(1,1), Vector2(1,-1), Vector2(-1,-1))
        tangents   as (Vector4) = (Vector4(-1,0,1,1), Vector4(1,0,1,1), Vector4(1,0,-1,1), Vector4(-1,0,-1,1))
        triangles  as (int)     = (0,1,3,3,1,2)

        mesh.vertices = vertices
        mesh.uv = uv
        mesh.tangents = tangents
        mesh.triangles = triangles

        mesh.RecalculateNormals()
        mesh.RecalculateBounds()
        mesh.Optimize()

        AssetDatabase.CreateAsset(mesh, destination)
        AssetDatabase.SaveAssets()

    meshFilter.mesh = mesh
    Selection.activeObject = customPlane

```

Gameobject \> Create Other \> Optimized Plane

---
Tags: unity, optimization
---


# Question
Title: How does Component Entity System Manages Game Mode?
I would like to create a simple game fire and shoot game using Component Entity System (CES). This game has two game modes(1): play mode and settings mode. The play mode is the actual game itself whereas the setting mode is where the player updates his sprite's settings, like type of weapon, inventories, etc.

Now, how does one implement game modes in CES? How would one switch to different game modes?

(1) The game mode i refer is something like the one implemented in Final Fantasy I, where it has four game modes (http://en.wikipedia.org/wiki/Final\_Fantasy\_(video\_game)#Gameplay)

# Answer
> 3 votes
Not everything must be components. If its easier fit you to build your Settings mode more traditionally, do that. Make a fun game, not a "perfect" architecture.

If you do want to make all your UI elements as components, consider using Spaces. Spaces are containers of game objects and systems. They're a very useful concept. Put your actual game in one space, your Setttings mode in another, your Pause screen in yet another, MainMenu in one, etc. Your objects stay separated, you can clear or reset a single Space at a time, and selectively update/render only the active Soace.

You can even have more than one Space running at once. Say you want some background action but don't want it interacting in any way with the main action. Spaces make that easy.

Each Space gets its own instance of any relevant systems. Given two spaces that both have physics, for example, there are two PhysicsSystems, one for each Space, managing the physics bodies in their respective Space independent of the other. With a third party physics library, this likely means creating a physics World for each space.

This is also useful for UI, since each space can remember its "global" properties like active element independently. You can switch between menus without the player losing his place each time.

---
Tags: entity-system
---


# Question
Title: How do I efficiently sort objects by draw order when rendering a 2D game?
I need to render a "tile" game with objects that overlap, because they are taller than the tile they stand on, like the games in these screenshots:

I don't know how to render them in the correct order. I intend to perform a sorting operation before every rendering, depending on the object's Y position. However, I'm worried it'll be too expensive, especially since very few objects change their Y positions.

Is sorting the most performant way? Is there any other way? What algorithm or data structure should I use?

# Answer
> 10 votes
When you have mobile objects and you want to get their draw order, there are two possible approaches how you can preprocess them before drawing:

1. Add a list of objects to each map tile. Iterate all objects and add them to the object list of the tile they are on. When you draw each tile, you first draw the tile itself, then sort its object list, then draw the objects, then delete the object list.
2. sort all objects by draw order. Then draw them all after drawing the map. Map tiles which obscure objects behind them need to be treated like objects in this case.

Option 1 is best when the objects move so quickly so they are in a different order every frame or when you have a lot of immobile objects, because you can then treat them like tiles.

Option 2 seems slow at first, but in most games you can make it a lot faster by using the right sorting algorithm.

In the majority of games, most of the time the object order will be the same or almost the same between two frames. In that case I would recommend you to use Insertion Sort. Usually it is considered a sub-par algorithm, but in the special case of data which is already nearly sorted it greatly outperforms all general-purpose sorting algorithms like quick-sort or merge-sort. I am using this method in the game I am currently developing. By replacing the standard Javascript sort with an own insertion-sort implementation I was able to reduce the execution time spent on object sorting from 3% to 0.2%, even though the default sort has the advantage of being implemented natively (measured in Firefox using the profiler of the Firebug extension).

# Answer
> 5 votes
I'd like to add that the *stability* of the sorting algorithm is also important.

When I first implemented sprite sorting in C# I used the built-in list sort method. This created a problem where overlapping sprites would flicker randomly when sharing the same Y value.

This happened because I used an *unstable* implementation of Quicksort, and the order in which those sprites were rendered would keep changing from frame to frame. I switched to a stable sorting algorithm and the problem went away.

I think I went with a Merge sort at the time, but Philipp makes a fine point about Insertion sort and its best case scenario, so I would look into that instead.

# Answer
> 4 votes
i would split it up into logical Layers

i.e.

```
BackGround
Tiles
Objects //People, trees etc.
Gui

```

draw each separately and place on top of each other

with the tile i would try to draw in order(topleft to bottom right), or define the the specific layer it should be drawn to (you can probably compute this from world coordinates (or tile index)

i would imagine the solution may vary from engine to engine but this would be how i approached it from an XNA / MonoGame pov

# Answer
> 1 votes
Just sort them. Use quicksort. (Usually that's the default sort on whichever language you're using.)

Just to give you an idea of the insignificance of thinking about other ways to do it: quick sorting 100,000 items will generally run in around 1 millisecond on modern hardware.

The only thing worth thinking about is that if your objects are huge, it's better to sort a list of pointers to your objects rather than the objects themselves (in order to prevent large copying.) Again, this is only a problem if you have megabytes of data.

# Answer
> 0 votes
I think you probably don't care.

If you have \< 100 (moving) objects in view, then sorting them is likely to be so fast that it's not important.

You don't need to sort objects outside the view, if you have thousands of objects in the world, but out of view, you should probably put your optimisation effort on culling instead of depth-sorting.

Objects which are permanently attached to ground tiles, don't need to be sorted (more than once) as they won't move around, right?

# Answer
> 0 votes
I would sort every frame, just as Philipp with his option 2 but using Bubble Sort. The advantage is that this is an in-place algorithm and it has the same advantage as insertion sort on already (almost) sorted lists. Which should save you some memory.

---
Tags: 2d, rendering, tiles, optimization, draw-order
---


title: Multipass shader in DirectX 11

text:
# Question
Title: Multipass shader in DirectX 11
As far as I understand for DirectX11 it is recommended to have multiple single pass shaders, so the the method with multiple passes in one shader file is deprecated. Is my understanding correct and where can I find more information about that?

How would I go about creating a multi pass shader in DirectX11? The way I understand it, one would have to apply a shader and then copy the shader result to be used as input for the next shader pass.

Is this the right way to do it? Any information on this subject is very appreciated.

# Answer
Multipass isn't going anywhere. The FX format and the whole techniques/passes syntax is best avoided, as the effects framework is now distributed only as source and a "real" engine can do things much faster and generally needs its own high level wrapper format anyway to manage its own shader/material/effects facilities. Probably using Cg as the main shader language (similar to HLSL) to ease porting to mobile, PS, Mac, Linux, and other non-D3D systems.
> 1 votes

# Answer
All a multi-pass shader really is is more than one separate set of shaders that operate on the same input data. For example, toon rendering is a common application of multi-pass shading, with two distinct passes:

1. Render the object
2. Render the object's outline

You can implement this by writing two sets of shaders, one for the object, one for the outline, and then rendering the same geometry with the same world transform, bones, etc. once per set.
> 3 votes

---
Tags: directx, directx11
---


# Question
Title: Controlling player and camera movement in a 3rd person game with keyboard and mouse
In many action games with a third person view, joystick controls typically map the left joystick for player movement and the right joystick for camera movement (or more precisely camera's direction towards the character). With first-person games, mapping to mouse/keyboard is easy because the camera is directly influenced by the player's movement. The player has to be able to look at any direction to point where he should go. Here is where the mouse comes in to provide this movement.

But the challenge I see is having separate camera and player controls with this setup. With a mouse/keyboard setup, it seems like I have to settle with a compromise, because the mouse is usually the only source for analog-like movement, whereas modern game pads have two sources, as separate joysticks.

One control scheme I had in mind is using A and D to change the player's heading as he travels through the world, leaving W and S to move forward/backward and the mouse free to move the camera. This still has a disadvantage, because you lack some degree to control how fast to change heading with the keyboard, unless you momentarily punch at the keys instead of holding them.

Is it possible to map the mouse and keyboard controls more intuitively for independent third person player and camera control?

# Answer
Typically I've seen the mouse used for both. Where a key on the keyboard or button on the mouse is held to change the modes. For example, the mouse without any other keys being held will control the player. Holding the right mouse button and moving the mouse controls the camera.

When the camera is not being directly controlled, it will follow the player in a typical hover/follow camera, common in other 3rd person games.
> 3 votes

# Answer
You could translate the first-person style directly to keyboard/mouse for third person by simply moving the camera behind the pivot point. So where a first-person shooter has the camera at the same point as the pivot, the third-person would set it back (facing the pivot). With this setup the keyboard controls the character movement and the mouse always controls where they look. Several games do this already, namely: The Witcher and WH40K Space Marine, among others.

If having the characters heading permanently stuck to the camera control is not what you want you can use a system like that implemented in WoW. They use a free camera most of the time that you can force your character to align with using a keypress. You could switch that and have the free camera mode be triggered by a keypress, or even toggle it on and off.

A third compromise option would be aligning the character with the camera during character movement. This would allow players to look around as long as they are not moving their character, but keep the character/camera controls easy for them to work with as they do not need to worry about extra button presses. I think Darksiders uses a camera control scheme similar to that.
> 2 votes

---
Tags: movement, input
---


title: Android game scrolling background

text:
# Question
Title: Android game scrolling background
I'm just trying to figure out the best approach for running a scolling background on an android device. The method I have so far.... its pretty laggy. I use threads, which I believe is not the best bet for android platforms

```
@Override
    public void run() {
        // Game Loop
        while(runningThread){
            //Scroll background down
            bgY += 1;

            try {
                this.postInvalidate();
                t.sleep(10);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

```

where postinvalidate in the onDraw function simply pushings the background image down

```
canvas.drawBitmap(backgroundImage, bgX, bgY, null);

```

Thanks in advance

---

**UPDATE & SOLUTION**

Thank you for everyone helping me. I came across this:

post https://stackoverflow.com/questions/1430741/how-to-draw-lots-of-bitmaps-on-screen-in-an-android-game-without-slow-performance

Helped my problem a lot. However, Seemed I was creating bitmaps in the onDraw every time is was caused, meaning that was doing 95% of the slowing down. oops :)

Below is my inner class in my surfaceview for reference purposes

```
class MapThread extends Thread{
    private Map map;
    private SurfaceHolder holder;
    private boolean run = false;

    public MapThread(Map map, SurfaceHolder holder){
        this.holder = holder;
        this.map = map;
        setRunning(true);
    }

    public void setRunning(boolean run){
        this.run = run;
    }

    @Override
    public void run(){
        while(run){
            try{
                Canvas c = null;

                 try {
                       c = holder.lockCanvas(null);
                       synchronized (holder) {
                            map.onDraw(c);
                     }
                 } finally {

                     if (c != null) {
                         holder.unlockCanvasAndPost(c);
                     }
                 }
        }
    }
}

```

# Answer
> 3 votes
There could be a variety of things causing your background scrolling to be choppy.

1. Your image could be very large causing `canvas.drawBitmap();` to be slow
2. Your loop could be firing slowly or inconsistently. I could be wrong, and maybe there are extenuating circumstances, but generally a `sleep();` call is never good in a game loop, or any loop for that matter. It could quite easily be the a contributor to your choppiness. I'd remove it to see what happens.
3. Other code you've stripped out from the example could be taking up lots of milliseconds in your loop.

I highly recommend you track the number of milliseconds between each iteration of your loop. You can use this data to determine how far to move your background based on how long the last loop took. This should smooth out your scrolling for the most part.

If the issue is because your image is so large that drawing it is taking up too much time, you may need to break the image up into smaller parts and "stream" it across the screen based on the scrolling position.

# Answer
> 3 votes
You might want to take a look at the Android Examples, specifically JetBoy:

http://developer.android.com/resources/samples/JetBoy/index.html

I believe they have scrolling backgrounds, specifically Parallax Scrolling (which you can look up here: http://en.wikipedia.org/wiki/Parallax\_scrolling)

But if you just want one background scroll, you could get a pretty good feel for how to do it from this game example.

(NOTE: I believe this game has scrolling backgrounds, correct me if I am wrong and I will edit this Answer)

EDIT:

You should definitely handle the drawing in a separate thread from the user input. Also depending on what version of Android you are building for, you might want to sleep in the input handling method for a couple milliseconds. You would want to do this because in earlier versions of Android, pressing the screen would result in a flood of inputs which would slow down the processing of an application. This was more acute in games. Check out the Replica Island code for more information on what I'm talking about.

Specifically if you look at: http://code.google.com/p/replicaisland/source/browse/trunk/src/com/replica/replicaisland/AndouKun.java on line: 344

```
@Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!mGame.isPaused()) {
                mGame.onTouchEvent(event);

                final long time = System.currentTimeMillis();
                if (event.getAction() == MotionEvent.ACTION_MOVE && time - mLastTouchTime < 32) {
                        // Sleep so that the main thread doesn't get flooded with UI events.
                        try {
                            Thread.sleep(32);
                        } catch (InterruptedException e) {
                            // No big deal if this sleep is interrupted.
                        }
                        mGame.getRenderer().waitDrawingComplete();
                }
                mLastTouchTime = time;
        }
        return true;
    }

```

Chris sleeps the input thread for 32 milliseconds which is approximately 30 sleeps per second (which matches 30 fps for the game). This makes sense because if you are only calling your update method once per frame, you don't need to have the input thread produce any more than 1 input for a touch event.

# Answer
> 2 votes
if you're still looking for a solution to the timing:

Read this article, specifically how the class `FPSTimer` is used in the draw thread to time the drawing loop. I've used this example to write my own surfaceview-based game. It also provides a good basis for handling key event inputs. For handling touch events, you would want to override the `View.OnTouchListener` for `DOWN`, `MOVE`, and `UP` events.

# Answer
> 1 votes
Don't use `Sleep` in the `onTouch`! On some devices, this will stall and crash because of the "sticky keys" function.

```
    if (startH == 0)
    startH = System.currentTimeMillis();

    // Keep speed down.. in time based style! 8-)
    if((System.currentTimeMillis()-startH)>=30 && startH != 0)
    {
        timeToProcess = true;
        startH = 0;
    }

```

That might be the problem.

---
Tags: 2d, java, android, game-loop
---


# Question
Title: Calculate intersection of a line with a plane
I was reading something about: “Intersection of a line with a plane”. But I don’t fully understand how to calculate it on their way.

The goal is to calculate where the plane and the line will “cross”. These items are given:

* The eye is in position: O(0,0,-10)
* A point of a 3D-object is P(10,20,30)
* The screen has the equation z=0

I have a questions about how they calculate this:

This part is clear. That is the location form the eye (vector representation).

They specify the location of the plane, there is nothing strange here (vector representation).

Now they calculate what part of the line will cross, how did they calculate this? How did they know a = 1/4? And b = 10/4?

This is everything that was given.

# Answer
linear systems of N variables can be solved if you have N equations.

```
x = 10ɑ
y = 20ɑ
z = -10 + 40ɑ
x = β
y = 2β + μ
z = 0

```

6 equations, 6 unknowns. You can solve for all 6. In fact, generally you can just combine the x/y/z parts and say

```
10ɑ = β
20ɑ = 2β + μ
-10 + 40ɑ = 0

```

and get 3-variable system in ɑ,β,μ. Once you get a value for ɑ, you can plug back in to Pintersection = PlineEye \+ ɑ * PlineDirection to get x,y, and z.
> 3 votes

# Answer
It's easier to think of this using vector maths.

The plane equation is `N.P = -D` for all points on the plane.

Therefore, the intersection point must satisfy this. If our point P is defined by the line equation `P = P0 + tQ` (where `Q` is the line's direction and t is the distance along the line) we can sub this in:

```
N.(P0 + tQ) = -D

```

The dot product is bilinear:

```
t(N.Q) + (N.P0) = -D

```

rearrange for `t`:

```
t(N.Q) = -D - N.P0
t = (-D - N.P0)/N.Q

```

and then plug your `t` back in to the line equation to get the crossing point.

From this we can intuitively read a couple of simple properties:

If the line's direction and the plane's normal are perpendicular there is no crossing. `N.Q` is zero, which would be a divide by zero.

`-D - N.P0` describes how 'far' `P0` is from the plane in the direction of the plane's normal. N.Q then describes the ratio between the direction of the plane and the direction of the line - the more parallel the direction and normal, the faster it will intersect.
> 3 votes

---
Tags: intersection
---


# Question
Title: C++ and OpenGL ES: glDrawArrays calls are time consuming
Currently, I'm profiling my iOS. All the calls to glDrawArrays are expensive. For example, here is a screenshot of the rendering part of a particle system:

As you can see, the `glDrawArrays` call takes from that method 39% of the CPU time. While other calls like `glUniform1i` and `glBindVertexArrayOES` are very quick. Why isn't `glDrawArrays` as quick as the others are? Aren't all these methods starting with `gl***` short functions that will add a command to the driver queue? So, why does it take longer for a `glDrawArrays` call to be added to the queue, in comparation with all the other gl calls?

Is this normal, or does this mean that I'm doing something wrong?

---

In response to *doug*: Nope, that didn't work. The glFinish() call actually took a while, but the `glDrawArrays` call is still taking much time in comparation with the state changes (like `glBindVertexArrayOES`).

# Answer
The way most drivers operate is by using a "lazy state changes" model. What this means is that the vast majority of your gl\* calls will actually do *nothing much* more than recording a state, storing off some parameters, then return immediately. This works perfectly fine up until a gl\* call is made that actually needs to *do* something with all that state (or that depends on the result of some other previously made call); at that point in time all the previously buffered-up state needs to be gathered together and flushed before the call can be made.

So what you're seeing is perfectly normal, if slightly misleading, behaviour: the time recorded for glDrawArrays is not actually the time taken by glDrawArrays *alone*, but also includes time for actually committing a whole bunch of previous GL calls.

There's a discussion of this for D3D available here but the same basic principle will apply to any modern implementation of either API. The key point to take away from it is: "in general, trying to profile your GPU by timing the CPU is going to be confusing and misleading".
> 8 votes

# Answer
You may be seeing the effects of queueing. Most likely the command queue blocks at that call because, for example, the queue is too full or you are getting ahead of vsync. It is probably doing a bunch of work from before the glDrawArrays call.

You could try putting a glFinish right before glDrawArrays, just to see if it is the commands in the queue taking the time or actually the glDrawArrays call. If the queueing effects are your actual performance bottleneck, it will blame glFinish instead of the innocent glDrawArrays call.

On the other hand, glDrawArrays may indeed be using a lot of CPU. I would try the above to be sure you're looking at the right thing.

EDIT: glFinish, NOT glFlush

***I AM NOT SAYING LEAVE THE glFlush CALL THERE.*** Come on guys, do you really think I am saying leave the glFlush call there? Its a ***performance investigation***.
> 1 votes

# Answer
Naive implementation of just writing to a command buffer on every gl call makes little sense, when the driver can possibly optimize out state changes. Thus, it makes sense to postpone processing as late as possible, especially on a tiled/binned rendering architecture, which most OpenGL ES implementations are.

On some architectures it actually makes sense to do some shader processing as late as on a glDrawArrays call. (And yes, even your ES1.x hardware likely has some form of shaders under the hood).

Calling glFinish/glFlush like doug65536 suggests won't help on tiled/binned architectures, as it causes a total pipeline flush which has a very, very, VERY heavy overhead on such - causing the rendering of everything queued so far to every tile and forcing a unresolve on the next render cycle.
> 0 votes

---
Tags: c++, opengl-es, performance
---


# Question
Title: How do I detect the intersection of a curve with itself?
I'm developing a game in which the player can draw a line. I want to detect if that line intersects with itself. How would I do this?

# Answer
> 3 votes
As the comments ask: *How are you representing your curve (i.e. "drawn line")?*

Anyway, *any representation* should be possible to convert into a list of points that represent the curve to some precision. It might look something like this:

# Naive algorithm

Go through adjacent point pairs and check if they intersect with another point pair that isn't the same.

```
function intersectsWithSelf(curvePoints)
    local points = curvePoints
    for i = 0, len(points) - 1 do

        -- Point pair 1
        local p1 = points[i]
        local p2 = points[i+1]

        for j = 0, len(points) - 1 do
            -- Point pair 2
            local p3 = points[j]
            local p4 = points[j+1]

            if p3 is not p1 then
                if intersects(p1,p2, p3,p4) then return true end
            end
        end
        return false
    end

```

In the innermost loop, the function `intersects` checks whether two line segments intersect. This has been solved in many interesting ways. It's been covered well before.

# Complex algorithms?

Your pictorial example would suggest the curves are quite simple. However, if you find that curves have to be long or their precision quite high, the polynomial time naive algorithm may be too slow. More advanced algorithms exist and some of them can solve the problem in logarithmic time by performing a sweep test. These are, of course, much more complex to implement.

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


title: How to rotate a direction

text:
# Question
Title: How to rotate a direction
I'm working a spotlight for my deferred renderer and I'm having trouble with matching the mesh to the visual representation of the light. Right now my mesh is a cone, the apex of the cone is at (0,0,0), it has a height of 1 and a radius of 1. The direction of this cone is (0,-1,0) when the rotation is (0,0,0).

The relevant GLSL code:

```
float spot_alpha = dot(-l,normalize(vec3(0,-1,0) )); // <------
float inner_alpha = cos(light.falloff);
float outer_alpha = cos(light.radius);
float spot = clamp((spot_alpha - outer_alpha) / (inner_alpha - outer_alpha),0.,1.);

```

As you can see, the GLSL code uses a direction to define the area to be lit, so I could get this direction as a uniform, but I would need to find a rotation from that for the mesh to follow, or I can get the rotation and find a direction, but I don't know how to do either of these things.

Can I rotate a direction? How do I do it? If I can't, is there another solution for this problem?

# Answer
> 3 votes
Assuming C++ with GLM...

C++:

```
//Construct a rotation matrix to rotate 'degrees' around a certain axis
glm::mat4 rotation = glm::rotate(glm::mat4(1.f), degrees, glm::vec3(/* axis */));

//Upload to shader 'program' as uniform 'rotation'
GLint loc = glGetUniformLocation(program, "rotation");
glUniformMatrix4fv(loc, 1, GL_FALSE, &rotation[0][0]);

```

GLSL:

```
uniform mat4 rotation;

...
//Rotate the vector
vec4 result = rotation*vec4(0,-1,0,1);
//Chop off the W component and normalize
vec3 direction = normalize(result.xyz);
//Use the rotated vector
float spot_alpha = dot(-l,direction);
...

```

Of course, you could also calculate `direction` entirely in the C++ code and just upload it.

---
Tags: opengl, mathematics, glsl
---


# Question
Title: Tile-based game with DirectX - issues with transparency and StretchRect
In my current project I have a class which loads a map file and then it should load all associated tilesets (no transparent tiles - I used to work with magenta as a colorkey) and precreate a surface for each static layer of the map so I only have to display one bigger image per frame rather then iterating over all of my tiles. For each tileset I have a loop which loads them successfully like this

```
 IDirect3DSurface9 *pTilesetSurface = nullptr;
 // Create surface
 HRESULT hResult = Engine::GetInstance()->GraphicsDevice->CreateOffscreenPlainSurface(
      pTileset->GetImage()->GetWidth(),
      pTileset->GetImage()->GetHeight(),
      D3DFMT_A8R8G8B8,
      D3DPOOL_DEFAULT,
      &pTilesetSurface,
      nullptr);
 if(!SUCCEEDED(hResult))
      return FALSE;

 // Load tileset
 std::wstring strTilesetSource(
      pTileset->GetImage()->GetSource().begin(),
      pTileset->GetImage()->GetSource().end());
 strTilesetSource = strPathToMap + strTilesetSource;
 hResult = ::D3DXLoadSurfaceFromFile(
      pTilesetSurface,
      nullptr,
      nullptr,
      strTilesetSource.c_str(),
      nullptr,
      D3DX_FILTER_LINEAR,
      D3DCOLOR_ARGB(255, 255, 0, 255),
      nullptr);
 if(!SUCCEEDED(hResult))
      return FALSE;

 this->m_vTilesets.push_back(pTilesetSurface);

```

After this loop I am iterating over every layer of the map and trying to build a surface for each layer with the associated tiles like this.

```
IDirect3DSurface9 *pLayerSurface = nullptr;
HRESULT hResult = Engine::GetInstance()->GraphicsDevice->CreateOffscreenPlainSurface(
    pLayer->GetWidth() * 16,
    pLayer->GetHeight() * 16,
    D3DFMT_A8R8G8B8,
    D3DPOOL_DEFAULT,
    &pLayerSurface,
    nullptr);
if(!SUCCEEDED(hResult))
    return FALSE;
Engine::GetInstance()->GraphicsDevice->ColorFill(
    pLayerSurface,
    nullptr,
    D3DCOLOR_ARGB(0, 0, 0, 0));
for(int x = 0; x < pLayer->GetWidth(); ++x) {
    for(int y = 0; y < pLayer->GetHeight(); ++y) {
        const Tmx::MapTile tile = pLayer->GetTile(x, y);
        if(tile.tilesetId != -1) {
            int dwTilesetWidth =
            this->m_pTmxFile->GetTileset(tile.tilesetId)->GetImage()->GetWidth() / 16;
            std::div_t tileCoords = std::div(tile.id, dwTilesetWidth);
            RECT srcRect = { tileCoords.rem * 16, tileCoords.quot * 16,
                tileCoords.rem * 16 + 16, tileCoords.quot * 16 + 16 };
            RECT destRect = { x * 16, y * 16, x * 16 + 16, y * 16 + 16 };
            Engine::GetInstance()->GraphicsDevice->StretchRect(
                this->m_vTilesets[tile.tilesetId],
                &srcRect,
                pLayerSurface,
                &destRect,
                D3DTEXF_NONE);
        }
    }
}

```

A call to `D3DXSaveSurfaceToFile` for debugging purposes creates transparent png files which can be layered correctly in Photoshop etc. but when I render these surfaces with this loop

```
for(auto iter = this->m_vLayers.begin(); iter != this->m_vLayers.end(); ++iter) {
    Engine::GetInstance()->GraphicsDevice->StretchRect(
        *iter,
        nullptr,
        Engine::GetInstance()->Backbuffer,
        nullptr,
        D3DTEXF_NONE);
}

```

then I have some wrong output which you can see here: .

All the blacks areas should be transparent such that one can see the layer below. **Has anyone an idea what I might be doing wrong?**

PS: I have read about the `IDirect3DTexture9` and `ID3DXSprite` interfaces which could be helpful, but I haven't used them yet as I did not find any information on how to rebuild a map with tiles like I did here with usual surfaces. If anyone has suggestions about this, I would be glad to here them!

# Answer
With the hint of mh01 and some trial and error I succeeded in drawing my map. I am still loading the tilesets as `IDirect3DSurface9` objects but creating `IDirect3DTexture9` objects for each layer. With a call to `IDirect3DTexture9::GetSurfaceLevel()` I retrieve a pointer to the underlying `IDirect3DSurface9` of the texture which can be used for `StretchRect`. However when I want to draw the layers I must not use `StretchRect` as it does not render but merely copy all contents. Therefore I am relying on a `ID3DXSprite` object which handles this for me successfully.
> 0 votes

# Answer
StretchRect just does a straight copy and so doesn't support any form of alpha blending; you're going to need to find another method of doing this.
> 0 votes

---
Tags: 2d, directx, rendering, tiles, transparency
---


# Question
Title: In OpenGL Shader, Why adding color change vertex position?
I have the following vertex shader:

```
#version 120

attribute vec4 position;
attribute vec4 acolor;

varying vec4 theColor;

void main(){
    gl_Position = position;
    //theColor = acolor;  //[1]
    theColor = vec4(1.0,0.0,0.0,1.0); //[2]
}

```

When I use line \[1\], the color is transmitted rigth to the fragment shader, but when I change the color to the attribute `acolor` (using the line \[2\]) the positions of the triangles appear wrong. From the data of the main program, it seems to me like the positions get the color values.

I put two images,  with the rigth vertex positions and  with the wrong vertex positions.

***UPDATE***: render code on Github

# Answer
> 2 votes
Check your glBindAttribLocation calls - you'll probably find that one of two things are happening; either (1) you're not doing any such calls and therefore GL is assigning it's own arbitrary attrib locations which are mismatching those used in your glVertexAttribPointer calls, or (2) you have specified a mismatch yourself.

Either way, the recommended approach would be to use "layout(location=" syntax in your vertex shader, which will make this kind of ambiguity go away.

---
Tags: opengl, shaders
---


# Question
Title: Cook Torrance model implementation : black specular light
I am trying to implement the Cook-Torrance model, and this is how I calculate the parameter Rs:

```
float Rs(float m,float F,vec3 N, vec3 L,vec3 V, vec3 H)
{
    float result;
    float NdotV= dot(N,V);
    float NdotH= dot(N,H);
    float NdotL= dot(N,L);
    float VdotH= dot(V,H);
    float Geom= min(min(1.0, (2.0*NdotV*NdotH)/VdotH), (2.0*NdotL*NdotH)/VdotH);
    float Rough= pow(1.0/(pow(m,2.0)*pow(NdotH,4.0)), ( pow(NdotH,2.0)-1.0)/( pow(m,2.0)*pow(NdotH,2.0)));
    float Fresnel= F + pow(1.0-VdotH,5.0) * (1.0-F);
    return (Fresnel * Rough * Geom)/(NdotV*NdotL);
}

```

I apply this formula:

Where I set m to 0.5 and F0 to 2.0.

But I think it's wrong because I'm getting a black area where there should be the specular light:

PS: With OpenGL 2.1, GLSL 1.20.

# Answer
> 2 votes
```
float Rough= pow(1.0/(pow(m,2.0)*pow(NdotH,4.0)), ( pow(NdotH,2.0)-1.0)/( pow(m,2.0)*pow(NdotH,2.0)));

```

Does not correctly reflect the formula for the `Roguhness` term. It should be something like:

```
float Rough= (1.0/(pow(m,2.0)*pow(NdotH,4.0)) * exp ( pow(NdotH,2.0)-1.0)/( pow(m,2.0)*pow(NdotH,2.0)));

```

that is, exp usually stands for `e` raised to the power `x` (e is the Euler number, the natural logarithm base, etc.)

---
Tags: opengl, glsl, lighting
---


# Question
Title: NPC AI articles for walking and fighting?
I'm looking to learn about NPC AI to solve a problem how an NPC should walk e.g. walking straight and then turn at a wall. Perhaps I can program it to walk along a line but then I still would not know how to make the NPC do more complex. An article I found is linked.

http://www.red3d.com/cwr/steer/

Can you link something more that could solve my problem?

## Update

I found this question constructive: How to handle walking into walls?

# Answer
> 1 votes
It sounds like you may want to investigate more fundamental concepts behind AI systems in general. The AI for a game is usually made up of many different components and decision making processes that are each custom tailored to their own particular context.

http://www.amazon.com/Programming-Game-Example-Mat-Buckland/dp/1556220782/ref=sr\_1\_1?ie=UTF8&qid=1360073834&sr=8-1&keywords=game+AI

This is a link to a book that myself, and a number of fellow graduate students find quite useful. The link you provided has some neat information at it, and quite a few links to other bits of useful information.

# Answer
> 2 votes
You could also been interested in this number of Game Career Guide: check the article at page 13, "Getting there from here". I know that's a simple introduction to AI, but it's well written and, if you have to start from the basis, it could be very useful. More than that, it provides some resources at the end.

---
Tags: algorithm, ai, npc
---


# Question
Title: How can I make sprites like diablo's for my soon-to-be isometric rpg? Like in all directions
(xna newcomer)I can use blender(3d modelling tool). I just can't make people, but if I have to, I'd learn it.

How can I do that? I plan on making a lot of armor sets, equipments too. How would I go on making the spritesheets?

***1 - How do I make the character display a different spritesheet when attacking/going up or down through the map? 2 - So I learned from a tutorial how to make spritefonts to save resources, but I don't know how to make a dialogue actually happen. I'd like to give the character two dialogue options like "I'll help you" "I'll not help you" and depending on the choice, the character that gives the quest dies some time later or not. can someone help ?***

Thanks in advance

# Answer
If you want a list of things to do to end up with sprites *like* what you end up with in Diablo / Diablo II / StarCraft / Fallout, then the first step is to create your 3D model, texture it, and animate it (walking, attacking, hurting, dying, etc).

Then, when all of that is done you want to set the camera to the same angle as what you would see in the game.

Then you would turn your model 45 degrees and save pictures of each stage of each animation, and keep doing that until you had pictures of every model, in every animation, from every angle.

To save space, things that didn't make sense to happen at every angle didn't.
Treasure chests were not shown from the back, et cetera.

Some games had characters that could look straight up and down, and straight left and right, but other games only used characters who were facing on 45 degree angles.

To add multiple kinds of armour, using the old-fashioned Diablo II procedure, you'd have to put each KIND of armour on your model, and save out all of the pictures in all of the poses in all of the directions.

I say "KIND" of armour, because most of the armour was just recoloured versions of the same model.

They did that recolouring in the game. So you'd make one kind of gauntlet, and add that to the model, and then in-game, you'd just recolour it.

BUT if each type of character needs to look different in chainmail, then you need to model each kind of character wearing chainmail.

There are more-modern ways of doing this... ...but if what you want is for the game to look like Diablo II, then this would be the way to accomplish it.

Saving all of this to a sprite-sheet is relatively simple:
You take all of the little pictures and you copy and paste them all into one big picture.

For the purposes of importing the sprite-sheet into the game and making it dynamically-usable, or for the purposes of using "masking" to change the colours of armour, et cetera, those are outside of the scope of your current problem.

Also, if this sounds like it's a lot of work to do manually, it really, really is.
But that's why you want to look into "Batch Processing". So that you can write a script that says "Take all of the versions of this model, and for each animation, save a picture every X % of the way through the animation, and name it
".png"

You could then write a batch process which would take all files in that folder, and put them in order, or put them out of order... ...or make one huge spritesheet, or just make one spritesheet per character, per armour type, et cetera.

A more-modern game might treat the character like a ragdoll.
> 2 votes

---
Tags: xna, 2d, sprites
---


# Question
Title: "Compose PSM Master Package" doesn't do anything
I made a game for PlayStation Mobile, and I'm ready to build the master for publishing.

Per the mastering instructions, I have filled out all the required information in app.xml, created app keys for this specific application, and built on Release.

And now that I click on "Compose PSM Master Package", the PSM Studio pretty much does nothing. I have .psdp and .pspp files in the Release folder, but I don't get a .psmp file for submission.

I think all my account information is okay, including bank account information.

I also tried deleting and recreating the app keys, but "Compose PSM Master Package" still refuses to do anything.

What am I missing? What kind of interaction should I expect from "Compose PSM Master Package"?

# Answer
Well, who knows what was it. Recreating my project from scratch worked. I kept the original project, and made a deep file comparison, and apart from the created project GUID, there were no other differences between the old and new projects.

Now my game is "Waiting for Review"

Regarding the expected interacion, as soon as you click on "Compose PSM Master Package", you get a login screen so you can log into PSM. Then you get a confirmation. After one or two minutes, you get confirmation that the master package was created.

So, who knows...
> 0 votes

---
Tags: psm, psm-studio
---


title: How important is engineering?

text:
# Question
Title: How important is engineering?
I'm a student at Ohio State, I hope to be a game developer one day, and I'm on track to be enrolled in the BS Computer Information and Science program in the Arts and Sciences department, but there's another major in the engineering department called Computer Science and Engineering. As you can see, they're virtually the same, except that CSE requires several courses in engineering and higher level math, whereas CIS requires more GE classes, like foreign language. CSE is also accredited, whereas CIS is not.

So I'm wondering, if I want to be a game developer, how important is a knowledge of engineering, if at all? Should I try and get into the CSE program or will I be fine in CIS?

# Answer
> 6 votes
Engineering is very important in game development because of many reasons. Specifcally talking about game development, you'll need to have a strong understanding about math (linear algebra, trigonometry, physics) and in your engineering course you'll get that. Besides, engineering is very important in any software development because you have to design, test, improve, innovate and think clearly. I'd choose Computer Science and Engineering.

# Answer
> 2 votes
The top two universities in my city ( and among the best in my country ) have two distinct faculties when it comes to computer science. One has the equivalent of your *BS Computer Information and Science*, and the other one ( the one I will finish next year ) has the *Computer Science and Engineering* equivalent. I have friends in both universities, and I study *Engineering*, so I have personal experience with both of them. Here's what I have to say about their distinction:

**Computer Information and Science:** It's has soft program. It revolves around fundamental programming concepts, more diversified mathematics, some business concepts, etc. It's also shorter in length ( doesn't seem to be the case for your university ). It has a leaner, more theoretical approach. From what I've noticed, most of the people graduating from this faculty end up web developers. That's no joke.

**Computer Science and Engineering:** This is the real deal. You get to learn everything from mechanics, digital electronics, computer architecture ( we built our own microprocessor based on the MIPS architecture ), low level assembly, all the way up to high level programming concepts such as Object Oriented Programming, functional programming, design patterns, etc. It's tough, it has a more practical approach, and it teaches you so much more.

I read somewhere that professional programmers need to know what they are working with, and that's the underlying hardware. I learned plenty of hardware in Engineering. I got a decent understanding of almost everything that makes a computer tick. From transistors, gates, memories, CPUs, caches how programs are compiled into machine code and how that code is run. Needless to say these are extremely valuable skills. And they help tremendously towards becoming a game developer, and a good programmer overall.

From a mathematics perspective, game development mostly requires linear algebra and to some lesser extend, calculus. At the university you mentioned, you only get the linear algebra course in the engineering program.

Your university's programs differ somewhat from what I'm familiar with, so you might not get the same experience. Even so, engineering will give you a more solid foundation overall and a better understanding of computers as machines rather than black boxes.

Also, always keep in mind that universities are more like guides. They will not make you an expert in any field. They will simply help you discover career options, and provide some foundations. Whatever program you choose, and whatever career you wish to pursue, the best way to learn and improve, is to study on your own. Read the books listed in the course bibliography. Read articles written by experienced programmers. Work on side projects. Put your passion to good use.

---
Tags: education
---


title: Stencil buffer and transparent pixels

text:
# Question
Title: Stencil buffer and transparent pixels
Do transparent pixels cause a stencil buffer operation (increment, decrement, etc.) to be executed?

My understanding was that only opaque pixels cause a stencil buffer operation, transparent pixels have no effect on the buffer. However in my application transparent pixels do seem to cause the stencil buffer to be written.

Do I have to set up a special blendstate in order to achieve transparent pixels to have no effect?

# Answer
DirectX9 was the last revision to support alpha-testing.

For DirectX10+:
In fact, transparent pixels do have an influence on the stencil buffer. In order to avoid altering the depth/stencil, you omit the pixel:

```
if (pixel.a < 0.1) discard;

clip(pixel.a < 0.1f ? -1 : 1); //omit if parameter evaluates to less than 0

clip(pixel.a - 0.1f);

```

This uses 0.1f to determine "close enough" similar to float.Epsilon.

**Be aware:** This disables early-z testing and may cause significant and/or unacceptable performance loss.
> 1 votes

---
Tags: directx, directx11
---


# Question
Title: XNA 4.0 storage framework not being recognized
This may be a silly question but, im unable to do any save game data because for some reason, this following namespace is unrecognizable:

```
 using Microsoft.Xna.Framework.Storage;

```

All the normal XNA namespaces work but not this one. Im ade sure to uninstall XNA 3.1, and the windows phone 7 SDK. Then i un-installed XNA 4.0 and reinstalled it. Im not sure whats wrong, but i would really enjoy some help so could get to saving some games.

# Answer
If this is for a Windows Phone project, you won't have access to that namespace. You'll want to use System.IO.IsolatedStorage for Windows Phone applications. See this tutorial on how to do that.

Further, ensure your target framework and the project match. The project and the references need to be the same version. If you're using XNA 4.0, you need to have created an XNA 4.0 project. If the project was created as a 3.1, you can't use the 4.0 references.
> 1 votes

---
Tags: xna-4.0, storage
---


# Question
Title: Bad FPS for smaller size (OpenGL ES with SDL)
If you saw my other question, well, there is still a little problem:

Click here to watch on youtube

Basically, the frame rate is very bad on the actual device, where for some reason the animation is scaled (it looks like the left side on the video). It is quite fast on the simulator where it is not scaled (right side).

For a test, I submitted this new changeset that simply hard-codes the smaller size (in SDL\_CreateWindow() and in glViewport()), and as you see in the video, now it is slow even in the simulator (left side shows the small size, right side shows the original size -- otherwise the code is the same).

I'm clueless why it's soooo slow with a smaller galaxy, in fact it should be FASTER.

The question is not about general speed optimization like reducing screen resolution or joining glBegin(GL\_POINTS)/glEnd() blocks.

**Update:** For a test, I simply reduced the screen size to 320x480 and compiled it to OS X desktop -- got the same speed as with 800x800, so this size-specific slow-down is on iOS only. Will post this on the SDL mailing list now.

# Answer
> 3 votes
Comparing iOS Simulator and OSX OpenGL speed is pointless. OpenGL ES on iOS Simulator is a software renderer, and OpenGL in OSX is GPU accelerated. The performance characteristics can thus be expected to be completely different.

More to the point, the faster image with the galaxy on the right side of the screen culls more than half of the points against the view frustum. That is a very fast operation and already there you should get 2x performance. Further, the amount of overdraw in the centered galaxy is far higher since you have a smaller galaxy with the same point size as the larger galaxy to the right. Each overdraw increase blending computations. You see that as the brightness increasing.

In short, you have 2x shading work and much more blending work. To remedy this, decrease the point size for the centered galaxy. You may also want to cut the number of points in half for the centered galaxy to get equal performance.

---
Tags: opengl, iphone, ios, opengl-es, sdl
---


# Question
Title: XNA Game arhitecture, sharing vertices between objects
I'm practicing primitives rendering in XNA and I want to create something like pipe or tunnel. I have base class called PipeSegment from which I inherit classes like RotatingSegment and NormalSegment (and whatever I imagine). To combine this segments I have created class called Pipe, which have List of PipeSegment objects.This is what I have so far :

It's ok, except the fact that I'm generating way more vertices than necessary. For each segment I'm generating 36 vertices for 'front side', and 36 for 'back side'.

Illustration :

Now, my question. How can I optimize this, how to generate less vertices ? Is there any way to 'share' vertices between Segments to preserve my current code structure and is my code structure suitable for this ?

Thanks

# Answer
> 1 votes
You could set up your DrawableGameComponents like links in a linked node list.

For instance, each PipeSegment would have a reference to the next PipeSegment in the line. Then when you want to draw the current PipeSegment you call some interface function that returns the vertices you need. RotatingSegment and NormalSegment implement the interface function however they want.

If all you're concerned with is not storing the data for the vertices multiple times, then you can just draw each segment separately at this point. If, however, you are trying to only make 1 draw call then you can have the segments all send there vertices to the first node through the list, then only make 1 draw call there.

# Answer
> 0 votes
I think the real problem here is the PipeSegment having any vertices at all. Rather the PipeSegment should have two Ring objects that are a collection of points around the pipe and are shared between adjacent PipeSegments. The rings would come in two flavors to offset the points.

---
Tags: xna, 3d, architecture, vertex-arrays
---


# Question
Title: Portable sound and music for XNA / MonoGame?
What is the best (recommended) way to integrate audio (both sound effect and music) in a game project (using C#/XNA) targeting multiple desktop platforms (W7, W8 Metro, Linux, OSX, ...) via MonoGame. XACT was the usual way in XNA but it is deprecated in W8 and also cannot be used with MonoGame, I am looking for an alternaive. Is there one?

# Answer
The "usual" way is to use the `SoundEffect` class. This will work on multiple platforms out of the box; it's done "the XNA way," so if you've used XNA, you should be familiar with how this works.

The only issue I found so far (tested on XP, Win7, and Android emulator) is that **sound doesn't work on XP.** I posted my long, painful saga (and solution) in this question and answer. (TLDR: OpenAL doesn't work on XP, so use NAudio for Windows instead.)
> 1 votes

---
Tags: xna, xna-4.0, sound, audio, monogame
---


# Question
Title: Are 2D art assets typically created at their intended in-game display size?
I'm wondering if game makers create their sprites smaller than their intended in-game size in order to be more efficient or whether doing that produces unacceptable quality.

# Answer
> 5 votes
If the asset is pixel art, then yes. Save it such that one pixel of the sprite is one pixel in the image, and then scale it up in game. This is a much more memory-efficient method of storing sprite art.

---

If the asset is not pixel art, I generally create the source graphic at a resolution higher than I would ever expect to use (usually something like 2-4 times larger), and then save the actual asset image at whatever size is necessary. If the asset image ends up being too small, I can always save a new copy from the source image.

Example: 512x512 .psd source, 128x128 .png asset

The only time I ever save the asset at a smaller resolution than what I actually want is when I know the image is going to be blurred in the game anyway. For example: something in the background that is designed to be out of focus will be something like 64x64 scaled up to 128x128 and blurred.

# Answer
> 1 votes
It really depends on the game and its art style. Some games use simple pixel art and scale that up to the intended in-game size. Other game makers create sprites for the game's default screen resolution and only scale them up for full screen mode. Generally, it really depends on how much time can be put into creating detailed sprites and/or how important it is for the game to have high quality art.

Based on the 2d flash games I've played and seen, sprites are typically created at their intended in-game display size, though this may vary per game platform.

---
Tags: 2d, sprites
---


# Question
Title: Centralized User database for multiple Systems
I was wondering, how do large companies handle user accounts and allow different applications to access them.

One example that comes to mind is Riot, their game League of Legends has a global user account that allows you to login to forums and the game client itself.

What sort of method would they be using to allow multiple systems to access this database.

# Answer
--- EDIT ---

*The answer assumes that you're going to use HTTP for communication between your game and your backend database.*

One choice would be to implement your own authentication and authorization mechanism.

Basically, you should have some sort of API on the backend system (database) and protect that via some auth mechanism:

> * signed requests
> * basic authentication (good for internal applications & consumers of the API)
> * oauth (good for external 3rd party consumers of the API)

Second choice is to use a platform that gives you backend as a service (BaaS). Most of these providers also give you a lot of security mechanism like oAuth server for instance and you don't have to worry for the backend infrastructure a lot. You just have to worry about how you're going to use it.

Checkout **apigee** and **Parse** for the second option.
> 2 votes

# Answer
It's probably the same way that you would do it with just the game - you have a database somewhere that both have access to. If they're really paranoid they might have one database as a mirror of the other, and when you sign up it copies your details across.

The larger problem for big companies is redundancy and sharding, to share the data across multiple servers so that they can load-balance the usage from everyone trying to access it. A lot of DB software has this built-in nowadays.
> 1 votes

---
Tags: databases
---


title: How free is BSD / CC-BY usage?

text:
# Question
Title: How free is BSD / CC-BY usage?
I looked at blendswap.com where there are models that I want to make walk along a wall in this level. AFAIK I can take this file and sell it or did I misunderstand licensing?

# Answer
Th CC-BY 3.0 terms are pretty clear in this regard:

> You are free:
>
> * to Share — to copy, distribute and transmit the work
> * to Remix — to adapt the work
> * to make commercial use of the work
>
> Under the following conditions:
>
> * Attribution — You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).

So yes, you can sell the CC-BY work from someone else, unmodified or modified. You just have to credit the author. And you don't have to release your work under the same license (the CC license which requires that is CC-BY-SA).

The BSD licenses (there are multiple of them) also allow you to use the work, even commecially and even under a different license. The difference is in the attribution clause. All BSD licenses demand that you give credit by including the original copyright notice. The 4-clause license (which is rarely used nowadays) also demands that you give credit in any advertising material:

> All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by \[organization\].

But beyond that, you have to be careful with giving any more credit than that, because the 4-clause and 3-clause BSD-licenses forbid you from using the names of the original authors to promote your product:

> Neither the name of the \[organization\] nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

The 2-clause BSD license doesn't contain this term. It only requires that the original copyright notice with the license terms stays intact.

Note that it is OK to state that the BSD license terms only apply to those parts which were made by the original authors, not to your modifications. Many proprietary software companies do that.
> 5 votes

---
Tags: licensing, jmonkeyengine
---


# Question
Title: How to have qt5 work on desktop like on mobile devices (es2, correct glsl version)?
I am looking for help/information concerning this issue :

My work: I have an opengl es2 render engine that works on an iOS app. I almost managed to make it work by calling the same openGL rendering engine from a Qt(4.8 first, then 5.0 since today) app with a QGLWidget. To support es2 function set my widget also inherits QGLFunctions (QtOpenGLFunctions with qt 5.0.0).

However I still have issues with shaders : I could not compile them on qt with glCompileShader because of almost every keywords (lowp, vec4, vec2 …) were returning compilations errors. So I compiled it with QOpenGLShader program, but I had to specify “#version 120”, the closest to es2. But still, my sprites don’t show up the right size and the only potentially influencing different pieces of code with iOS are in shader compilation / version. I think the issue in the shader is that gl\_PointSize is not taken into account.

Is there any better way for me to have shaders compiled on qt like they are on iOS ? ( I know glsl es2 version is coming from version 120 but I don’t know to what extent they differ ). The hello-gl-es2 example did not help me because glsl version also returns 1.20.

I’ll happily receive any hints, thank you !

My shaders, working well on iOS but not on Qt:

```
const GLchar vShaderStr[] =
#ifdef  __BUILD_DESKTOP__
"#version 120\n" // necessary for Qt to compile shaders
#endif //__BUILD_DESKTOP__
"attribute lowp vec4 Position;\n"
"attribute mediump vec2 TextureCoord;\n"
"attribute lowp float Weight;\n"
"uniform mat4 MVP;\n"
"varying mediump vec2 TextureCoordOut;\n"
"void main(void)\n"
"{\n"
"  gl_Position = MVP * Position;\n"
"  TextureCoordOut = TextureCoord;\n"
"  gl_PointSize = Weight;\n"
"}\n";

const GLchar fShaderStr[] =
#ifdef  __BUILD_DESKTOP__
"#version 120\n" // necessary for Qt to compile shaders
#endif //__BUILD_DESKTOP__
"varying mediump vec2 TextureCoordOut;\n"
"uniform sampler2D Sampler;\n"
"uniform bool IsSprite;\n"
"uniform lowp vec3 TextureColor;\n"
"uniform lowp float Opacity;\n"
"void main(void)\n"
"{\n"
"   lowp vec4 textureColorResult;\n"
"   textureColorResult = texture2D(Sampler,  IsSprite ? gl_PointCoord : TextureCoordOut);\n"
"   gl_FragColor = IsSprite ? vec4(mix(textureColorResult.rgb,TextureColor, 1.0),\n"
"                    textureColorResult.a * Opacity) : textureColorResult;\n"
"}\n";

```

Edit : replaced preprocessor QT\_OPENGL\_LIB with custom **BUILD\_DESKTOP** as the first is no more declared in qt5.

# Answer
> 0 votes
Finally solved this issue !

I kept the #version 120 and found what was missing for it to work as it does on device. On desktop with qt(5.0 now) you have to activate following gl functions that seem to be default on iOS:

```
  glEnable(GL_POINT_SPRITE);
  glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);

```

---
Tags: shaders, glsl, opengl-es2, qt
---


title: SDL.NET vs SDL C++

text:
# Question
Title: SDL.NET vs SDL C++
I am currently transitioning from XNA to SDL, and was wondering if SDL.NET provides the same benefits as SDL C++.

Considering that SDL.NET uses the .NET framework as a wrapper to the SDL base libraries, I would assume that this creates less portable code.

If I want to be able to compile my source to multiple platforms, would it be best for me to stick with C++ ? Or will SDL.NET provide the same benefits?

# Answer
.NET Framework is availble on other operating systems if you use Mono. If your problems are just about cross-platformness, I would highly suggest you use MonoDevelop.

However, it seems SDL.NET has some issues with Mono, at least on Android.

I suggest you do some research about SDL.NET and Mono and see if would be OK to use this match-up.
> 3 votes

---
Tags: c++, sdl, .net
---


# Question
Title: Run a physics simulation on both client and server?
I'm implementing a multiplayer asteroids clone to learn about client/server network architecture in games. I have spent time reading GafferOnGames and Valve's publications on their client/server tech. I am having trouble with two concepts.

1. Currently I have an authoritative game server simulating physics with box2d and sending out the state of the world to clients about 20 times per second. Each client keeps track of the last few snapshots it received and lerps between two states to smooth out the movement of sprites. However it's not that smooth. It can be smooth for a while, then jerky a bit, then back to smooth, etc. I have tried both TCP and UDP, both are about the same. Any idea what my problem might be? (Note: I implemented this for single player first, and the sprite movement is perfectly smooth at 60fps when updating the physics world only 20 times per second).
2. In order to solve the first problem I thought maybe the client should run a box2d simulation as well and just update the positions of its sprites to match the server snapshots when they don't match. I thought this might be smoother since my single player implementation is smooth. Is this a good idea?

Even if it won't fix the above problem, is it necessary for client-side prediction? For example, if a player attempts to move their ship, how will they know if they hit an asteroid, wall, or enemy ship without a physics simulation? It seems like their ship would appear to pass through the object it should collide with before they receive a snapshot from the server that says they hit the object.

Thanks!

# Answer
> 10 votes
Definitely run the simulation on both the clients and the server. Anything else have too long latency. You should be sure that the simulations match by inserting objects in the same order, using a fixed time step and avoiding pointer comparison. I haven't tried this with Box2D but it is generally possible to achieve the same behavior on all machines in a physics simulation. All math is usually based on IEEE 754 binary32 floats and their behavior is strictly defined for operations such as `+-*/` to name a few. You need to be careful about `sin`, `cos` and the likes tough, since they can differ between runtimes (this is especially important when developing for multiple platforms). Also make sure that you use a strict setting for float optimizations in your compiler. You can still synchronize objects by periodically sending out the state of objects from the server. Don't update unless the difference is larger than a threshold to avoid unnecessary stuttering.

One issue that come to mind is the creation of new objects and how that will change the simulation between clients. One way to fix this is letting the server create all objects. If the current time step is `t`, the server will schedule a object to be added at `t+d`. Thus, a new-object list, with objects to add and when to add them, can be can be maintained at all the clients and updated by the server well in advance. If `d` is large enough, you minimize the risk of different results. If you really can't handle difference you can force a client to wait for information about new objects for a certain time step before simulating that time step.

# Answer
> 4 votes
It probably doesn't look so good since interpolating between them relies on always having the next set of data to interpolate to. This means that, if there's a short lag spike, everything has to wait to catch up.

There's an old article on GameDev about using cubic splines to predict the position of an object past the point where you last had data for it. What you then do is use that position and then adjust the spline when you get new data to account for its new position. It's also probably much cheaper than running a second physics simulation, and it means that you don't have to decide about who you trust, since you've explicitly implemented the client making it up as it goes along. :)

# Answer
> 1 votes
I've done some similar stuff myself, and I ran Box2D on only the clients. The way I did it was to let the client run its own simulation pretty much on its own, sending the current velocity (and rotation) on every sync packet to the server. The server then sends this information to other players, who set the newly-received velocities to the replicated entities. It was very smooth, without any noticeable differences between clients.

Of course, the problem here is that there's no centralized control over entities, but I think that could be done on the server side as well by doing server-side simulation of the physics as well

# Answer
> 1 votes
I would personally prefer to run the simulations only on the server and have it broadcast any changes on linear/angular speeds/accelerations of the involved objects whenever they happen. It is, when a certain object, for any reason, changes any of it's physical properties (such as the aforementioned speeds and accelerations), this specific change will be sent from the server to the client, and the client will change it's side of the object's data accordingly.

The advantage of it over your current implementation is that it will void the necessity of clientside interpolations and will generate a very faithful behavior on the objects. The problem is that this method is quite very vulnerable to latencies, which become a very big problem when the players are geographically too far away from each other.

As for the question 1, I's say the problem would be fluctuations on the latency, because there is no absolute guarantee that there will be an exactly perfect 20 second interval between each receiving of the snapshot. Let me illustrate (being "t" the time measured in milliseconds):

1)At t = 20 since the game's start, the client received a snapshot and did the interpolation succesfully and smoothly.

2)At t = 40, there was a latency between the server and the client, and the snapshot happened to only actually arrive at t= 41.

3)At t= 60, the server sent another snapshot, but one second of the simulation was wasted clientside because of the latency. If the snapshot arrives at t= 60, the client will not do an interpolation of the 40 and 60 instants, but actually from instants 41 to 60, generating a different behavior. This inexactness on might be cause of the eventual "jerkiness".

As for question 2, your idea might work if you implement something that will efficiently track whether each object are really client-server synchronized without having to send packages each frame informing the position of the objects. Even if you do it at discrete intervals, you will not only run on the same problem of the question 1, but also have too big quantities of data to be transferred around (which is a bad thing).

---
Tags: physics, networking
---


# Question
Title: How do I calculate consistent frame timings at 60fps?
I'm writing an HTML canvas game that uses requestAnimationFrame and therefore runs at 60fps, although this is more of a question about failing arithmetic than about JavaScript.

If I measure the time since the last frame in order to update my sprite positions correctly, I get a slight jitter in the movements. This is because the times are accurate to the millisecond, and 1/60s does not neatly fall on millisecond boundaries.

What I end up seeing are timings like this:

```
16, 17, 17, 16, 17, 17, 16, 17, 17, 16

```

(In reality I get more 16s than 17s because of time spent outside of the timed region of code, but you get the idea).

This timing difference means that on each frame that updates on a perfect 1/60 monitor refresh rate, I advance my sprites at an imperfect rate.

My solution is to lie about my timing. I'd like to round my timings to the nearest multiple of 1/60s, expressed in ms.

E.g. If I get around 16ms timings, I'd like to report 16. If I get around about 33ms timings (1 dropped frame), I'd like to report 33.

Is there a magical formula that will do this?

# Answer
```
var ms = 17 // this frame's step
var step = (1/60) * 1000 // this is your desired step
var dt = ((ms / step)|0)*step // calculate number of 'steps' in ms, truncate it to an int, multiply by step

```

This will fix a timestep to a multiple of 1/60. If you wanted an integer dt, just truncate again using `dt|0`.

I'd advise against this, though. I would either find a more accurate timing method than what you're using or fix your timestep rather than a halfway house.
> 7 votes

# Answer
1) You cannot rely on any fixed rounding technique : some screens are 60Hz, some 50Hz, or even 100Hz or 120Hz (like mine), ... not to mention mobiles that might be 30Hz, 20Hz,...

2) the error of the rAF might be in fact greater than 0/1, might be 2, and if the garbage collector occurs, you might even miss a frame or two, even on a Desktop : your code has to handle this nicely.

3) For this reason and to allow to pause the game, you have to use your own game time, and not real-world time to compute the right frame in your animation :

```
// each rAF you do something like :
var now   = Date.now() | 0;
var delta = (now - this.previousCallTime);
if (delta < 14 ) { return };       // max rate is 66Hz.
if (delta > 60 ) { delta = 16; };  // if too many frames missed,
                                   //     consider only 1 frame elapsed
game.time   = game.time + delta ;
this.previousCallTime = now;

```

3) And now compute the frame with :

```
var frameIndex =  ( ( (game.time - this.animStartGameTime )
                                  / this.animFrameDuration ) | 0)  % this.FrameCount ;

```

4) So let us see an example with 60Hz, and 3 step 20Hz anim (=50ms) :

```
 frame time       16  17 17  16   17  17  17   16  17  16
 animtation time  16  33  50  66  83  100 117  133 150
 animation index  0   0   0   1    1   *2*   2   2   0

```

Ooops , the animation is choppy, we have 3 frame 0, but only 2 frame 1, then 3 frame 2 again... !!!

But you know what ? Sadly enough this is an issue that **cannot be solved** : you are trying to approximate a fixed integer by a sum of random integers : whatever you do there WILL be times when you do not have the regularity you seek.

the effect can be *reduced* if you take a higher number of frames, but only reduced.

The solution provided by Matt Kemp is not what you seek :
1. Yes, you will have regularity on the index (0,1,2,0,..,0,1,2,..) but the time each frame last will be different, so for a hero walking for instance, the player will feel like the walking speed is changing over time, which is noticable also, so you trade one glitch for another, which is **far far worse** with 2+ ms jitter + garbage collection occuring : the real-world case.
2. It works only in 60Hz, which is a no-go.

So if you are very sensitive to animation quality, use 8, 12, 15 frames/seconds or more, this is the **only *real* solution**.

Rq : most LCD TV do this kind of computation to handle NTSC/PAL/... 's different framerate with the same screen frequency : it is not noticeable.

I put a small code i wrote before into a JSFiddle so you can experiment and see by your self : change the parameters or the index computation function, and you will see there is no way to get around this, you can just improve by raising the number of frames.

Here : http://jsbin.com/ewowel/2/edit

Results :

```
"Anim same frame count (index trunced) : 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6"
"Anim same frame count  mean : 6 error : 0"

"Anim same frame count (index trunced) : 6,6,7,6,6,6,6,6,6,6,6,6,5,6,6,6,6,6,6,7,6,6,6,5"   "Anim same frame count  mean : 6 error : 4"

"Anim same frame count (index trunced) : 7,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6"
"Anim same frame count  mean : 6 error : 2"

```
> 4 votes

---
Tags: mathematics, javascript, rendering, game-loop, frame-rate
---


title: Resolving a collision with forces

text:
# Question
Title: Resolving a collision with forces
In my 2D physics engine, I can detect AABB vs AABB collisions, and resolve them by finding the shortest penetration vector and adding it to the AABB's position.

Doing this "pushes" the first AABB outside of the second AABB, but doesn't deal with velocity/acceleration changes at all.

If I add gravity acceleration to my simulation, the velocity of the first dynamic AABB keeps growing even when it is resting on top of the second static AABB. Eventually, the velocity will become too big and the collision won't be detected (the dynamic AABB will fall through the static one).

I tried setting the velocity to zero after resolution, but it obviously didn't work well, and created unrealistic simulations.

I read online that resolving collisions by manually working on the position or the velocity is not correct. I tried implementing forces (mass is an "hardcoded" 1 for now):

```
void Body::applyForce(sf::Vector2f mForce) { acceleration += mForce; }

void Body::integrate(float mFrameTime)
{
    velocity += acceleration * mFrameTime;
    position += velocity * mFrameTime;

    acceleration = {0, 0};
}

```

If I apply the shortest penetration vector as a force during collision resolution, the dynamic AABB will get "pushed out" from the static one, but its velocity will never decrease in a simulation without gravity and it will keep moving forever.

Is there a way to apply a "temporary" force? A force that deals with pushing the first AABB out of the second AABB, then stops when the AABB doesn't collide anymore?

Entire source code available here: https://github.com/SuperV1234/SSVSCollision

# Answer
> 15 votes
*First, I recommend using a free, open-source physics library like Box2D and just focusing on the aspects of your game that make it unique! If you insist on re-inventing the wheel, read on... note all physics engines are approximations, and while the method I outline below will be more accurate than your current model, Box2D's results will be far more realistic.*

---

## For a quick way to model more accurate collision resolution of two objects A and B:

1. **Find the positions right before the collision.** You are already approximating this by: "finding the shortest penetration vector and adding it to the AABB's position."
2. **Find the velocities right after the collision** using Newtonian physics:
    * For the case where mass is hard-coded as 1, simply swap the velocities (this does not apply to static objects which must have infinite mass):
        + A.v = B.u
        + B.v = A.u
    * If objects A and B have different masses:
        + A.v = (A.u * (A.m - B.m) + (2 * B.m * B.u)) / (A.m + B.m)
        + B.v = (B.u * (B.m - A.m) + (2 * A.m * A.u)) / (A.m + B.m)
    * where:
        + v: velocity after collision
        + u: velocity before collision
        + m: mass (use the largest number possible for the mass of a fixed, static object)
3. **Set acceleration to 0:** The acceleration from the collision was accounted for above by the velocity calculations in step number 2.

Please take a look at my sample asteroids program which demonstrates these concepts.

---

## Next, account for stacked objects:

As you have noted, using velocity to simulate stacked/resting objects does not work well: velocity is the speed an object is moving, so if it is resting on a static object, velocity should be near 0. It does not make sense to increase the velocity of an object to make it appear at rest:

> If I add gravity acceleration to my simulation, the velocity of the first dynamic AABB keeps growing even when it is resting on top of the second static AABB. Eventually, the velocity will become too big and the collision won't be detected (the dynamic AABB will fall through the static one).

What should really happen is an acceleration force that is going in the opposite direction as gravity should cancel gravity out. (This is called the normal contact force). A shortcut is to simply not apply gravity to bodies that are not in the air:

* One method of doing this by is keeping a "grounded" state:
    + Do not apply gravity to objects in a grounded state.
    + If an object collides with an object from below and its velocity is very small it enters the grounded state.
    + An object exits the grounded state when its vertical velocity exceeds a certain positive value.

---

## Update:

* In layman's terms, Newtonian physics says the total energy before and after a collision must match. When two objects crash into each other, their energy is redistributed. Energy is a combination of speed and weight: heavier, faster things have more energy. That's intuitive. However, what's not intuitive is the exact way weights affect the energy redistribution.
* Swapping velocities is a shortcut only for two dynamic, unfixed bodies that have the same mass (static, fixed objects have very large, infinite masses).
* The shortcut when one static body is fixed is: the other dynamic, unfixed body keeps the same speed; only angle is changed (imagine a pool table when a ball hits the rail. The rail essentially has a very large, infinite mass).
* For other cases, like three or more objects, the full Newtonian motion equations must be solved (conservation of momentum and conservation of kinetic energy).
* I'm not sure if the Newtonian equations for motion can be solved for more than two bodies. Fortunately, however, three objects almost never collide at the exact same time. It is sufficient to handle the first two bodies that collide, then handle any following collisions using the new velocities from the previous collision resolutions. This is a good reason to keep your physics time steps as small as possible and handle collisions before any penetrations occur.
* You'll notice in my asteroids demo many bodies are created as bigger rocks are split into smaller ones. However, I always handle collisions between pairs of bodies; never explicitly handling a collision with more than two bodies.

# Answer
> 16 votes
Solving this problem requires adjusting position and possibly velocity. Rigid body physics engines have a solver that march objects forward in time using Newton's laws of motion while also solving non-penetration constraints and friction. These engines can compute the right combination of linear and angular motion to create plausible trajectories.

If you only want to resolve overlap, you can use pseudo velocities that generate separating trajectories without adding to momentum. This is done in Box2D's position solver.

I recommend getting my GDC presentations from 2006 and 2007 here:

http://code.google.com/p/box2d/downloads/list

Also, you can look at Box2D Lite for a simplified implementation.

# Answer
> 2 votes
In the real world, there is no force that "pushes" one body outside of another body because objects don't ever penetrate each other. The closest thing is the normal force: created at the moment of contact in real-world collisions, it prevents penetration in the first place.

The angle of this normal force is perpendicular to the contact surface of the two colliding objects. The magnitude depends on how much force is needed to prevent penetration. (Note only the y component of the normal force should be used unless other forces like the friction force are also modeled).

While is is possible to explicitly model the normal force, it is simpler to model only its effects:

1. Prevent object intersection by either:
    * Adjusting velocities by resolving collisions at the moment of impact. (best)
    * Manually adjusting the positions of the bodies so they do not intersect. (easier) You're already doing this "by finding the shortest penetration vector and adding it to the AABB's position."
2. Do not apply gravity where there would be a normal force canceling out the gravity force.
    * An object in contact with another object below it is subject to the normal force. Thus it is a matter of keeping track of those objects. (Actually any objects that are in contact should have a normal force applied, but not all of these will have a net effect with respect to gravity.)
    * If you want to add objects that can slide down other objects that are at an angle, you will have to add the friction force and x component of the normal force.

I described this slightly differently in my other answer which is more about collisions in general.

---
Tags: collision-detection, physics, physics-engine, collision-resolution
---