title: 3D game engines for XNA games

text:
# Question
Title: 3D game engines for XNA games
Before I start development of an XNA game, I need to choose a 3D game engine to develop upon. Is this belief unfounded? Does XNA have basic object transformation, lighting and mesh/texture importing functionality by which you can develop a decent 3D side-scrolling game?

Chances are I'm going to need a 3D engine such as Torque X to handle most of the special effects, animation and sound for me. What are the engines that you recommend building an XNA game with? What work reliably in your experience? Is XNA alone enough? do you have repositories of code that work directly with XNA to create effects and other game environments with sunlight, fog and rain?

# Answer
> 24 votes
In short, the most **usable** 3D game engines written in fully managed C# code (which allows you to develop for the Windows and Xbox 360) are:

* **Ox Game Engine** \- a 3d version of the ButterMilk 2d engine - excellent features, Jiggle physics, reasonable scene editor, shadows. **Free**.

* **SunBurn** \- AAA rendering with dynamic lighting & shadowing, occulusion, HDR rendering, spectacular, diffuse and bump maps, and includes a 3D Game world editor to edit models, lights, materials. **$150** or more. **Free** version also available.

I would have mentioned **Torque X** on the top list but the negative response has been so overwhelming that I'm quite convinced it really a mess.

The other engines are listed here:

**Open Source**

3D

2D

* Flat Red Ball \- 2.5d game engine thats been around since the Managed DirectX days. Very well updated and supported.
* Jemgine \- 2D game engine with level editor, components, visual scripting language
* Box2D.XNA \- A C# port of the Box2D engine
* DEngine \- 2D tile engine with basic editor

**Commercial game engines**

* Kitae \- 2D game engine with tile/level editor, collision detection, sprites, fonts, etc.
* TorqueX \- (not recommended)
    + 2D - TorqueX Game Builder to edit levels from a drag and drop UI.
    + 3D - TorqueX World Builder to build 3D game levels with objects and lighting
* Visual3d.net \- (Windows only)

**Specialist**

**Physics Engines**

If you require code that will run on Xbox 360 or Zune then you need a 100% managed engine.

Most of these are free, or are free wrappers around commercial products.

If you are only targetting **windows** then you can use any of these:

* PhysX
* ODE (Open Dyamics Engine)
    + XPA (XNA Physics lib): XnaDevRu has a nice wrapper for, but it's majorly outdated and ODE is rumored to be bad/unstable. There's very little information about it, but the API is pretty friendly. Pretty easy to get up and running with simple collisions (even I made it!), but its hard to find what you need when problems occur, and its updated very slowly.
* Newton Game Dynamics

# Answer
> 3 votes
XNA offers everything you need to get your models on the screen. Its content pipeline is unmatched by anything I have seen so far. However, the interface to the rendering subsystems is fairly low-level, and you will most likely end up pushing a model's meshes to the hardware "by hand".

A good engine will help you batch submeshes with the same materials, handle transparent polygons and all that jazz. Adding a good scene manager will ensure that you do not send geometry that cannot be seen to the hardware. You can code all these things yourself, or you can get a rendering engine to do it for you.

And we haven't even considered things other than rendering, such as sound and physics.

You will find a wealth of interesting links on the XNA developer's Survival Kit (XDSK).

# Answer
> 3 votes
I highly recommend checking out FlatRedBall, as the engine is pretty straightforward, frequently updated, and the development team offers great support. I worked with the A.R.E.S.: Extinction Agenda development team while they were using FRB, and they had nothing but high praise.

Here are a few links to get you started:

# Answer
> 2 votes
You can develop a 3D game without the need of using an existing game engine as XNA gives you plenty of classes for that.

But if you really want to use a 3D engine, your best bet right now is using the SunBurn Engine:

http://www.synapsegaming.com/

Version 1.X is only a lighting engine, but Synapse has said that version 2.X will be a full game engine.

# Answer
> 0 votes
I would use Torque X now because it's fully featured. But thats if they still have it $150 or under because it supports Windows Phone 7 with Torque dev community.

---
Tags: xna, windows, xbox360
---


# Question
Title: Change collision body position in Bullet Physics Hello World project
I have got stupid and annoying problem in my app. I am using bullet physics and I've started with hello world example on wiki: http://bulletphysics.org/mediawiki-1.5.8/index.php/Hello\_World

There is someting like this:

```
btDefaultMotionState* fallMotionState =
            new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,50,0)));

```

What is described as set object 50m above something. So I can change the height but nothing more. I can't move it left, right - anything. Also when I set 0 everywhere ( I mean in btVector3) the object is jumping up rather than falling down or better stay still.

Can someone help me with that?

Also are there any materials except those on bullets page where are some tutorials or something?

**EDIT**

The main thing which I want to achive is to move my object for example left not only top or bottom.

Hope It will help in understanding.

# Answer
> 0 votes
The btVector3 class should let you move the object sideways by changing the first or third (X and Z) parameters. The tutorial assumes that you understand vector math.

Also, when you set 0 in all btVector3's, that makes the sphere intersect the plane halfway through, because they are both in the origin. This means a collision is already happening during initialization. That's probably why the sphere object is jumping up, because it has responded to the collision.

Setting up rigid bodies with a finite mass in a way that they're alrady intersect each other during initialization can have unexpected results in their movement. Usually, the only rigid bodies that can overlap without moving are the ones with "infinite" mass, and these are usually for static scenery objects.

---
Tags: c++, bullet-physics
---


title: How to record gameplay on WP7?

text:
# Question
Title: How to record gameplay on WP7?
I need to record my wp7 game gameplay like on Hot Apps from channel 9 http://channel9.msdn.com/Shows/Hot-Apps/Hot-Apps-Minesweeper-Cheezia-Interior-Design-Talking-Alien-Zombie-Squish.

My current game is written on Silverlight, but I will have XNA games latter as well, so I need some solution which will work for both technologies. If there any free software? If yes is there any way to record video from real device, not emulator?

# Answer
CamStudio will allow you to record video from your computer for free. This is probably the best solution, since I don't know of any way to record video from a Windows Phone on the phone itself. Though you could point a camera at the phone and record things that way.
> 2 votes

# Answer
Have you considered looking into integrating replays into your game instead?

I posted this question a while back on StackOverflow a while back which garnered some good replies.

*Edit*

Replays have many more secondary benefits that span from debugging and testing, to demoing, to supporting casting for esports (for a phone game, not a big deal, I know).
> 1 votes

# Answer
Fraps works really well for capturing the high frame rate in games
> 0 votes

---
Tags: windows-phone-7, game-recording
---


# Question
Title: Should I write my own game engine, and if so what are the main features?
> **Possible Duplicate:**
> When to roll your own game engine?

I've been interested in writting games for a while, and now that I have acquired a bit of experience in programming, I feel like I could step up to making a little more complicated things. I've had some fun with SFML but since now I only had the basic classes I needed for my game objects, and a big run() method of my Game object to "run them all".

I've only written gameplay tests so far, but I feel like a complete game in the same style of programming would be a gigantic headhache source. I am now facing a problem/question : should I be considering creating my own little "game engine", learning through it, adding features as I need them ? I think it could be a really good experience, but it would certainly take time as I'm no professional, and I don't have a clear view of "how-to" yet.

I am using SFML with C++.

# Answer
> 1 votes
from my point of view no!

surely writing your own engine will help you a lot, but if you are new to programming and specially game development, you don't need what you need to implement! and besides, engines are written to provide useful features with minimum performance loss. as you say you are new to programming so you still don't know how to optimize critical sections of your code.

so in general developing an engine is a good learning opportunity, but you need to know a lot of things to be able to start developing one! it's just like trying to learn programming with C++. Although you can do anything with C++ and almost all professional game developers get their jobs done using it (don't argue I said almost!), no one recommends it for the first language to learn, since a programmer without experience could break the whole thing easily without even noticing what was wrong!

---
Tags: c++, sfml
---


# Question
Title: How would I get the positon of my avatar's head?
I'm developing an XNA Game. Basically, I have a first person camera. What I want to do is get the position of an avatar's head. The reason I want to do that is because I want the camera to be on the avatar's head thus, giving it a real life view (you can see the hands and that type of stuff.

# Answer
Usually you just say "my character is X meters tall" and put the camera there. For the player's hands you have a custom model that looks good from first person that's separate from what other people see in the world (assuming you can see other avatars).
> 2 votes

---
Tags: xna, xbox, avatar
---


# Question
Title: How can I implement a "boost pad" with Farseer/Box2D physics?
I'm trying to implement a boost pad in my XNA game using the Farseer Physics Engine. (This question applies to Box2D too, I would be happy to port working Box2D code to C#.)

By "boost pad", I mean an object that can apply a force to the player that makes him go faster than he usually can under normal circumstances. These are most often seen in non-realistic racing games (e.g., Mario Kart, F-Zero). (For the record, my particular game is a 2D side-scroller.)

I use a very simple Farseer physics Body for my player: it's just a square shape with basic linear velocity.

Normally, I move my player like this:

```
body.ApplyForce(ConvertUnits.ToSimUnits(force));

```

Then, in my Update loop method, I cap the player velocity like this (to make sure the player speed never goes above `maxSpeed`):

```
float speed = body.LinearVelocity.Length();
if (speed > maxSpeed)
    body.LinearVelocity = (maxSpeed / speed) * velocity;

```

I'm struggling to think of a good way to implement a boost pad. The issues:

* What would be a good way to enforce two separate max speeds? There's one maximum speed for forces that are applied by normal player input, and another maximum speed for forces applied by boost pads.
* If the character is going faster than the normal max speed (e.g., they just hit a boost pad), how can I still allow the player to influence his *direction* without increasing his overall speed?

# Answer
> 1 votes
I wouldn't cap the player velocity like that. Instead, cap the velocity vector that comes out of your steering behaviour(s), and then apply any extra forces (ie. from explosions, boost pads, etc.). You can then cap those extra forces before combining them with the forces coming from your steering behaviours.

*edit*

For example, something like:

```
var desiredVelocity = Vector2.Zero;
if (/* player can control */)
{
    desiredVelocity =
        Vector2.Normalize(target - this.CurrentPosition) * this.MaxSpeed;
}

var additionalVelocity = Vector2.Zero;
if (/* criteria for "boosting" */)
    additionalVelocity = /* whatever you want */

var resultantVelocity = desiredVelocity + additionalVelocity;

```

An example of a time when a player might not be able to apply a force might be if they are airborne for eg.

I took this code from my game, which has an overhead perspective, but your `target` could just be a unit vector to the left or right of the `CurrentPosition`, or anywhere if there was a jetpack or something.

# Answer
> 1 votes
I gave this a try and the results I got look fine to me. Here's a video of what It looks like (although YouTube messed up the framerate).

The only thing I did was **multiply both the maximum speed and the forces by some arbitrary boost multiplier**.

1. Multiplying the **maximum speed** addresses your first question - The two separate maximum speeds become `maxSpeed`and `maxSpeed * boostMultiplier` respectively.
2. But I noticed that the body lost responsiveness due to the increased speed. Multiplying the **forces** by the same ratio seemed to solve the problem. The body is still as responsive as before.

If the video seems to be what you're looking for, here's the code:

```
bool hasBoost = Keyboard.GetState().IsKeyDown(Keys.Space);
float boostMultiplier = hasBoost ? 4f : 1f;

if (Keyboard.GetState().IsKeyDown(Keys.Left))
    body.ApplyForce(new Vector2(-1, 0) * boostMultiplier); // Notice the multiplier
if (Keyboard.GetState().IsKeyDown(Keys.Right))
     body.ApplyForce(new Vector2(1, 0) * boostMultiplier);
if (Keyboard.GetState().IsKeyDown(Keys.Up))
     body.ApplyForce(new Vector2(0, -1) * boostMultiplier);
if (Keyboard.GetState().IsKeyDown(Keys.Down))
    body.ApplyForce(new Vector2(0, 1) * boostMultiplier);

float speed = body.LinearVelocity.Length();
if (speed > maxSpeed * boostMultiplier) // Here too and on the next line
    body.LinearVelocity = body.LinearVelocity / speed * maxSpeed * boostMultiplier;

world.Step(Math.Min((float)gameTime.ElapsedGameTime.TotalSeconds, (1f / 30f)));

```

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


# Question
Title: Need Feedback for PHP & MySQL Saving Game Progress
My team is planning to create a simulation game using Javascript, CodeIgniter and MySQL for the backend.

It will be mostly click based, ie: There will be buttons for activities like Eat, Play, Study, etc, and in the game environment, one day will contain 3 phases, day, noon, night . And for each phase, users can pick between those activities and those activities will increase certain character parameters (Intelligence, Focus, Fun, etc) then the game will progress to the next phase. Once it's night, the game will progress to the next day.

So I need feedbacks on how to saving the game progress. Here's what I had in mind :

There will be a table for Users (obviously) that will contain users' data including the parameters/stats, money, etc. Do you think the stats etc must be separated to another table so there will be a history of stat increases?

For the saving, I'm thinking of using a Logs table that record every activity is by users. So if in day 1 phase 1 (phase day) the user picks Eat, I will insert to this logs table more or less like : user\_id = 1, day = 1, phase = 1, activity = eat. So for example when the user stops playing and exits the game after day 1 phase night, the database will have :

```
user_id = 1, day = 1, phase = 1, activity = eat
user_id = 1, day = 1, phase = 2, activity = play
user_id = 1, day = 1, phase = 3, activity = sleep

```

And when they continue the game, I will read from this table and get the latest row of this user\_id, and after checking that the latest row is day 1 phase 3, the game interface will display day 2 phase 1. However, this means that the phases for a day must be fixed from the start, so I can't include, for example, random additional time phases outside these phases (think of it as an extra opportunity to increase the stats).

So what do you think? I hope the explanation is clear enough.

# Answer
Because of the problem you mentioned I would recommend you to simply keep track of the current day and phase of the user separately, instead of trying to compute it from the `Logs` table everytime.

The simplest solution is just adding these fields to the `Users` table:

```
user_id = 1, current_day = 30, current_phase = 3, other_stats...

```

That makes things easier than the process you described and you just need to update those values whenever there's a phase change. Other than that, it seems okay to me. Also...

> Do you think the stats etc must be separated to another table so there will be a history of stat increases?

If the only way that users can increase their stats is through activities, then you *already* have a history of stat changes in the `Logs` table. Just keep the total current stats on the `Users` table for ease of use.
> 1 votes

---
Tags: databases, php, sql
---


# Question
Title: Looking for an Open Source Game Engine with Crowd Simulation
I am looking for a game engine for my school project on computer graphics. There are specific requirements that I do not want to implement by myself, since they are irrelevant for the grade, but relevant for the final result.

So reusing other one's code is a good thing here and I am looking for an engine that supports the following features, or that has plugins/3rd party projects available that can do it for me. I have already been looking for it for 2 days, but maybe some of you might just know the right fit for me.

Requirements:

* Open Source / Free \[so people can always view back my code without any licensing.\]
* 3D
* OO \[I'm not so good at C++. Preferred are: Java, C#\]
* Crowd Simulation \[I need walking people in my scene. This could be a 3rd party lib. Probably best with nav meshes.\]
* Render to Texture \[I need panels with moving images on it. Unity3d fails here.\]
* Multi-project \[I cannot adjust the installation folder on my school computer. UDK and CryEngine fail here.\]
* Networking
* Cross Platform (at least for Linux)

Engines that fail my requirements:

* CryEngine 3
* UDK
* Unity3d
* OpenSceneGraph: not a real engine. I need more interactive components.
* XNA: not cross platform.

**Update**
I found a nice crowd simulation lib after a long long search: http://gamma.cs.unc.edu/RVO2/ So that is not a big issue anymore

**Update 2**
Apparently, my mentor wants it to be cross platform. Which is an ouch for XNA.

# Answer
> 1 votes
I decided to go for the Delta3D engine. It can be built on any platform using `make`. Unfortunately it is in C++, so I'll just have to do my best to understand everything.

The Crowd simulation of RVO2 fits in very well and seems to cause no trouble.

It is open source and can easily be used over multiple projects. The engine is not included inside the project folder, but is installed separately on the computer.

It also has python bindings, so I could even do it in Python.

There are also connections with animation libs, networking and CEGUI.

# Answer
> 1 votes
Xen is open-source, C# and XNA and has crowd simulation plus lots more.

---
Tags: open-source
---


# Question
Title: Is it possible to animate the texture of a model?
Below is how far I've got. I just made a simple block with user primitives to test it. But I haven't found a way to crop the spritesheet.

```
textureLava = frames[activeFrame];

```

This line is how I want it but off course this doesn't work. Is there a way to crop this spritesheet or is there another way to animate the texture of a model?

```
public void CreateFrames()
{
    for (int i = 0; i < 64; i++)
    {
        frames.Add(new Rectangle(WIDTH + i, i, WIDTH, HEIGHT));
    }
}

public override void Update(GameTime gameTime)
{
    if (System.Environment.TickCount - lastFrameTime > TIME_BETWEEN_FRAMES)
    {
        activeFrame++;
        lastFrameTime = System.Environment.TickCount;

        if (activeFrame > 15)
        {
            activeFrame = 0;
        }
    }

    textureLava = frames[activeFrame]; --> DOESN'T WORK

    base.Update(gameTime);
}

public override void Draw(GameTime gameTime)
{
    effect.TextureEnabled = true;
    effect.World = Matrix.Identity;
    effect.View = Camera.ActiveCamera.View;
    effect.Projection = Camera.ActiveCamera.Projection;

    effect.Texture = textureLava;

    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
    {
        pass.Apply();

        GraphicsDevice.SetVertexBuffer(vertexBuffer);

        GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 10);
    }
}

```

# Answer
The problem is probably that `textureLava` is of type `Texture2D` while `frames` is an array of `Rectangle` objects. Obviously, you can't assign a `Rectangle` to a `Texture2D`. This is due to the fact that you're using a spritesheet for your lava animation directly. Three ways I cant think of to solve this:

**Solution 1 - Put each frame in a separate file**

The most simple solution for this problem would be to move each frame of the animation into a *separate* file and load each of them into a separate texture object (e.g. into an array of `Texture2D` objects).

**Solution 2 - Copy regions of the spritesheet into separate Textures**

If *really* want to use the spritesheet, another solution is to use the Texture2D.GetData and Texture2D.SetData methods to create the individual texture objects using a subset of the data contained in the original spritesheet texture. In other words, copy rectangles of data from the spritesheet into separate textures.

Something like this (which I have wrote from memory so it's untested but should be close enough):

```
Texture2D spritesheet = Content.Load("lavaSpritehseet");
List<Texture2D> frames = new List<Texture2D>();
List<Rectangle> rectangles = new List<Rectangle>(); // Load your rectangles here

foreach(Rectangle rectangle in rectangles)
{
    // Get data from spritesheet using the frame rectangle as a source
    Color[] data = new Color[rectangle.Width * rectangle.Height];
    spritesheet.GetData(0, rectangle, data, 0, rectangle.Width * rectangle.Height);

    // Create a new texture and assign the data to it
    Texture2D texture = new Texture2D(GraphicsDevice, rectangle.Width, rectangle.Height);
    texture.SetData(data);

    // Store frame
    frames.Add(texture);
}

// Now you can do lavaTexture = frames[activeFrame]
// Because they're both of the same type

```

**Solution 3 - Modify the vertices' texture coordinates**

There's also another alternative which would basically be modifying the texture coordinates of your vertices to match the cropped region. This could either be done on the GPU with a custom vertex shader that would receive the source rectangle and texture size as inputs and perform the cropping internally, or on the CPU by changing them directly on your vertex buffer.

This is not too complicated, but since the solutions above are probably enough for you, I'll leave it just at a general description:

* Your vertices have a Vector2 holding the texture coordinates. A value of `(0, 0)` represents the top-left corner of the texture and a value of `(1, 1)` represents the bottom right corner of the texture.
* If you want to only draw a portion of the texture, you'd change those texture coordinates to something else.
* For instance, if the spritesheet had size `(w, h)` and you wanted to texture using only the rectangle `(x, y, rw, rh)`, then instead of using a texture coordinate of `(0, 0)` for the top-left corner you'd use `(x/w, y/h)` and instead of `(1, 1)` for the bottom-right corner you'd use `((x+rw)/w, (y+rh)/h))`.

---

**PS:** Your way of updating the animation rate is also very bad. Don't use `System.Environment.TickCount`. Make use of the `gameTime` parameter of the `Update` method which carries information about how much time passed since the previous frame. I do it similar to this:

```
int totalFrames = 5;
int currentFrame = 0;
int framerate = 12;     // Animate at 12 frames per second
float timer = 0.0f;

public void Update(GameTime gameTime)
{
    timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
    if (timer >= (1.0f / framerate ))
    {
        timer -= 1.0f / framerate ;
        currentFrame = (currentFrame + 1) % totalFrames;
    }
}

```
> 2 votes

---
Tags: xna, c#, textures
---


# Question
Title: Offsetting image position when scaling in XNA
What Im trying to do is pretty simple, offset the rendering position of my image when scaled up/down. I honestly can't remember how to-do this :(

```
if (newAnim.texture != null)
{
    // Set Source Rectangle
    sourceRect.X = newAnim.imageRectArray[newAnim.CurrentFrame].X;
    sourceRect.Y = newAnim.imageRectArray[newAnim.CurrentFrame].Y;
    sourceRect.Width = newAnim.imageRectArray[newAnim.CurrentFrame].Width;
    sourceRect.Height = newAnim.imageRectArray[newAnim.CurrentFrame].Height;

    // Get new center when scaled.
    Vector2 center = new Vector2(
        (newAnim.imageVector2Array[newAnim.CurrentFrame].X * scale) / 2,
        (newAnim.imageVector2Array[newAnim.CurrentFrame].Y * scale) / 2
    );

    // Only Render if we have Something to use
    if (newAnim.CurrentFrame >= 0)
        spriteBatch.Draw(
            newAnim.texture, new Vector2(100, 100), sourceRect,
            Color.White, 0f, center, 1f, SpriteEffects.None, 0f
        );

```

I'm unsure what I need to do to the `Vector2`. Hopefully getting the center/origin position is correct? I think so.

**Edit:**

http://dl.dropbox.com/u/13874083/screenshots/screen120107-160918.png

The bigger image is the scaled image (pretty obvious :P), but both are rendered at 100, 100.

# Answer
> 1 votes
Since we reached the conclusion that you're simply trying to implement a zooming behavior, here's the most simple camera class possible with `Zoom` and `Origin`. By default this will be the middle of the screen:

```
public class Camera
{
    public Camera(Viewport viewport)
    {
        Origin = new Vector2(viewport.Width / 2.0f, viewport.Height / 2.0f);
        Zoom = 1.0f;
    }

    public float Zoom { get; set; }
    public Vector2 Origin { get; set; }

    public Matrix ViewMatrix
    {
        get
        {
            return Matrix.CreateTranslation(new Vector3(-Origin, 0.0f)) *
                   Matrix.CreateScale(Zoom, Zoom, 1) *
                   Matrix.CreateTranslation(new Vector3(Origin, 0.0f));
        }
    }
}

```

And here's an example of how to use it. Notice both sprites are being drawn exactly with the same parameters (except for the color):

```
Camera camera = new Camera(GraphicsDevice.Viewport);
camera.Origin = Vector2.Zero;

Vector2 position = new Vector2(100, 100);
Vector2 origin = new Vector2(texture.Width, texture.Height) / 2f;

camera.Zoom = 1f;
spriteBatch.Begin(0, null, null, null, null, null, camera.ViewMatrix);
spriteBatch.Draw(texture, position, null, Color.LightBlue, 0f, origin, 1f, SpriteEffects.None, 0f);
spriteBatch.End();

camera.Zoom = 3f;
spriteBatch.Begin(0, null, null, null, null, null, camera.ViewMatrix);
spriteBatch.Draw(texture, position, null, Color.LightCoral, 0f, origin, 1f, SpriteEffects.None, 0f);
spriteBatch.End();

```

Which results in the following picture:

In this example I set the camera origin to be `Vector2.Zero` since it matches the behavior on your screenshot. But normally, it would be better to zoom around the center of the screen, in which case just don't set any `Origin`.

Give both a try, and if you decide that you really don't need an `Origin`, then simply use the scale matrix `Matrix.CreateScale(Zoom, Zoom, 1)` directly. **You don't need to calculate new positions or origins for the sprites!**

---

**PS - About the origin of your sprites**

> Hopefully getting the center/origin position is correct?

Not really. If you want the origin to be the center of the sprite, and since you're using source rectangles, your origin should be:

```
Vector2 origin = new Vector2(sourceRect.Width, sourceRect.Height) / 2f;

```

The origin is defined in local (or model) space so it doesn't matter if you're scaling the entire scene or even the individual sprites, the origin still won't change.

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


title: Texture antialiasing?

text:
# Question
Title: Texture antialiasing?
In my Minecraft-clone style game, blocks are textured with a border that is lighter then the block color. See picture below:

To achieve this effect without the textures being blurry I use this code:

```
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

```

Without setting the MAG\_FILTER to GL\_NEAREST, it looks like this:

This is ugly and blurry. The upper picture (with GL\_NEAREST enabled) is obviously superior. My issue is that the edges in the upper picture are aliased (it is more obvious if you view the photo full-size.)

Is there any way to anti-alias textures? It does not look very good if the borders are aliased like this. Alternatively, is there any way to get rid of the aliasing on the borders?

Thank you for any help!

# Answer
Well, the simplest way to do it is use a higher-resolution texture, together with a full mip chain, trilinear filtering, and you'll probably want to turn on anisotropic filtering as well; that should give you smooth edges without (as much) over-blurring.

Another approach would be to use distance field textures, which are specifically for two-tone images (in the paper, for text rendering, where the two tones are the text color and transparent). They are able to get sharp, but aliased edges at any level of magnification. This should work for minification too although they only touch on it in the paper.
> 5 votes

# Answer
If you were to employ post-process antialiasing such as SMAA, it would not differentiate between geometric edges and texel edges. This might be sufficient in conjunction with the nearest neighbor texture filtering.
> 5 votes

---
Tags: opengl, java, minecraft-modding, lwjgl
---


# Question
Title: Which things to do in AutoCAD and which in 3ds Max?
I learned 3ds Max two months ago. I am not perfect in it, but I used it to make a model of a house. I am interested in house architectures. I used to model everything in Max.

I have just started to learn AutoCAD and it has been two weeks. I realized that AutoCAD is very accurate in modelling floor plans, doors, windows, etc.

The teacher told me that every thing from a chair to a pen to a bed, etc., can be modelled in AutoCAD.

Now I am confused as to which is the right way to model house interiors, AutoCAD or Max.

I want to know at what point should I finish things in Autocad and then move to Max?

# Answer
> 1 votes
It probably depends on what it's for and what your employee is telling you to do (if you get to that stage). If this is just for yourself, don't bother with Autocad, just use Max, it's so much more fun. Max and Maya are great tools for 3d visualization, I've seen some wicked home interiors made with these packages. You can model everything in Max for visualization, but if you need technical specs then Autocad might be the way to go.

Listen to what anyone says about Autocad, because I don't know it much, I've studied Max and to a lesser degree Maya. So an autocad user might have some things to consider.

# Answer
> 0 votes
It's been a long time since I've used AutoCAD. However, I believe AutoCAD is designed more towards professional architects that plan on drafting blueprints along with visuals whereas Max is mostly visuals with the ability to get really creative at design time and designed for artists.

The target audience of AutoCAD and it's functionality may have changed since my experience while working as a land surveyor.

# Answer
> 0 votes
simply when the need for high prisition AutoCAD better for drafting 3DMax better. I working with CAD and Max you can drow in CAD and Modifying in MAX and rendering because MAX is Faster in rendering

---
Tags: 3dsmax
---


# Question
Title: how to create a Quaternion from an Orientation Vector in xna
I have a Vector3 represents an Orientation in 3D , how to convert it to the corresponding Quaternion ? Is there any quick way ?

EDIT : I want to add an angular velocity vector to the Orientation Quaternion of the body

# Answer
> 5 votes
If your `Vector3` stores an euler angle `(yaw, pitch, roll)` you can use the following static method directly:

```
Quaternion quaternion = Quaternion.CreateFromYawPitchRoll(vector.X, vector.Y, vector.Z);

```

On the other hand, if you're not storing an euler angle, but just the direction (or forward vector) of the camera/object, then bear in mind that generally a single 3D vector is not enough to store a complete orientation in 3D space *unless* you restrict one of the axes of rotation.

A typical case is where your camera/object can't roll or flip around and the Up vector is always pointing in the upper direction, e.g. FPS camera. If that's the case, then you should create a rotation matrix from your forward vector, and then use the following static method:

```
Quaternion quaternion = Quaternion.CreateFromRotationMatrix(matrix);

```

As for creating that rotation matrix, I think something like this should work (I hope so, I'm a little rusty with cross products):

```
Matrix matrix = Matrix.Identity;
matrix.Forward = vector;
matrix.Right = Vector3.Normalize(Vector3.Cross(matrix.Forward, Vector3.Up));
matrix.Up = Vector3.Cross(matrix.Right, matrix.Forward);

```

I think this may cause problems though if you try to look directly up or down, or close to those orientations, so you may need to handle those cases separatedly.

---
Tags: xna, vector, quaternion
---


# Question
Title: How to "swing" bounding box and update collision for sprite swinging a weapon?
I have a simple question about sprite swinging weapons. I am making an RPG and would like something other than stabby-swords, so why not swinging swords?

I have a bounding rectangle for them, and the player equips them. Great, but I cannot grasp around my head how to swing both the sprite AND the bounding box (in XNA).

The sprite is easy, I specify it's origin and rotate by a specified amount over a certain amount of time (the swing time), but the bounding rectangle poses another issue for me.

**Edit:** A bit of clarity on my swinging animation. It's basically the player holding out their arm and the weapon swings in a curve from about +45 degree angle to a -45 degree angle.

# Answer
Top-down Zelda style? One way to approach and simplify the problem is to instead of using an entire bounding box for the sword, reduce it to just one or two points of contact (lying inside the sword) and rotate them instead. In fact, the tip of the sword should be more than enough to detect most hits!

I've seen this used before in a few games. For instance this Muramasa-like sidescroller game made in XNA used points to handle player-enemy collisions. If I remember correctly from one of his YouTube comments, he placed collision points manually in each frame of the animations, and then uses them to detect hits with enemies.

In your case there's not much variation between frames. Just assign a single point to the sword's tip. When performing a stab, move that point back and forth along the player's Forward vector. When performing a slash, rotate it around the player. That's the only tricky part, which I'll describe below - rotating the point around the player no matter what transformations he has.

---

**Implementation - How to rotate a point around the player**

The easiest way to rotate a point around the player is to start with its definition in local space, i.e. in relation to the player, and then apply a series of transformations to get it into world space. This is not too hard to achieve. Here's a possible implementation:

**(Step 1)**

Calculate the player's world matrix. This is just a regular SRT matrix (scale-rotation-transform). Here's an example:

```
private Matrix GetPlayerWorldMatrix()
{
    return Matrix.CreateScale(_playerScale, _playerScale, 1f) *
           Matrix.CreateRotationZ(_playerRotation) *
           Matrix.CreateTranslation(new Vector3(_playerPosition, 0f));
}

```

If your player can't rotate and/or scale just remove the corresponding lines.

**(Step 2)**

Start with the sword's position in local space, rotate it, and then apply the player's transform to it in order to get the final, world space position. It's simpler than it looks! Here's the code:

```
Vector2 localSword = new Vector2(0, _swordDistance);
Matrix swordMatrix = Matrix.CreateRotationZ(_swordRotation) * GetPlayerWorldMatrix();
Vector2 swordPosition = Vector2.Transform(localSword, swordMatrix);

```

All you need to do is interpolate the `_swordRotation` value when doing the swing.

**(Step 3)**

In my case I used the `swordPosition` for rendering so that you could see where it's placed, but in your case you should use that position for collision detection and hitting your mobs. Check the video and source code below for more details.

**Video:** http://www.youtube.com/watch?v=JoTxu-yiJKg
> 5 votes

---
Tags: xna, c#, animation, sprites, bounding-boxes
---


title: How to animate a model in WebGL?

text:
# Question
Title: How to animate a model in WebGL?
I created a human model in Blender, exported the vertices and indices into a JSON file and render the model in a browser using WebGL. Now I created a walk and jump animation in Blender and would like to do the same with WebGL.

I saw examples that use a list of vertices for every frame of the animation. Is this the way to go? Do I need to export the vertices for every frame for every animation?

# Answer
You need to implement either something like bones or morphs. As stephelton suggests, a WebGL framework would make this easier.

Since you're using Blender, how about using three.js ?

It already has a Blender exporter and there is also a python script to convert objs to the json format the framework uses, in case you need to use other applications.

Among great other projects, it was used for Ro.me and you can see samples of morphs there. You can have a look at the source code for the models as well.
> 7 votes

# Answer
You want to employ some kind of skeletal animation system. I suggest you find a WebGL framework to support this.
> 1 votes

---
Tags: opengl, animation, blender, webgl
---


title: Why even use shaders?

text:
# Question
Title: Why even use shaders?
assuming I want my game to have a Cel-shaded look. There are plenty of tutorials how to implement Cel-shading in hlsl f.e. But what is the point? If I am creating my assets with Blender or 3d-max I have a lot of possibilities to add materials and shaders in the modeling software.

So why write shaders?

# Answer
First, ok-to-good question. Definitely not a bad question. To answer it, you just have to know what a shader is and why you need one.

A shader is exactly what it sounds like - it "shades" vertices and pixels different colors. "Shading" isn't just "making it darker" (as the technical artistic term means I believe), it's *application of textures, lighting, and everything else that gives a vertex it's final color*.

"Shading" often makes the most sense if you think about some *light source*. You can't really have toon shading without a light source. You have to have light (and an angle to the light) to know how to shade an object in that light. And that's the job of the shader.

So, now you have a vertex/pixel shader that will do toon shading in Blender. Great. Why do you need to know HLSL if you can make a toon shader in Blender?

**If Blender exports HLSL code that you can plug into XNA, then you don't need to write the HLSL yourself**. You are correct. You wouldn't need to hear about, see, or touch HLSL code if Blender exports it for you. But I'm not sure if Blender can do that.

So if Blender *does not* HLSL shading code, then you need to write a toon shader in HLSL *because* all you'd get **is the model and vertices and their respective solid colors**, but you *wouldn't* get "how it should look at every single angle and under every possible light source" right - *that* needs to be computed at runtime (by a shader).
> 8 votes

# Answer
Materials made for a 3D modeling program won't translate directly into the materials used in your game. You would have to construct a content pipeline for your Blender or 3DS assets, or use one that's pre-made, and then you have to tell the hardware how to use the data extracted in these assets to display the graphics. That is what shaders are responsible for. Your program cannot guess exactly how these files are supposed to be used.

Shaders are especially useful in applying screen-space effects, which do not take in regard the geometry in the scene, at least not discreetly. Even if you use BasicEffect in XNA, you are using some sort of shader, just a pre-built one.

Unlike DirectX 9, XNA does not have a fixed function pipeline. So even diffuse texturing is a very simple use of a shader. There are ways to minimize shader use, by using the 3D modeling software to bake the effects to your models as textures, such as ambient occlusion. But these tricks do not work well for dynamic scenes.
> 4 votes

# Answer
Shaders are not only used to draw textures and effects on an object, would you for example be able to create a motion blur without shaders? Besides, most materials in 3DS max have shaders underneath to create the texture with its effect.
> 0 votes

---
Tags: xna, shaders, blender
---


# Question
Title: What are the requirements for a sound file in android?
I am creating a game in Android and eventually I am going to outsource the sound effects. I have a few place holder sounds for testing and I have noticed a problem. I have an OGG sound file which plays correctly through the emulator/headphones but when I put it on my phone it doesn't play. Putting my ear right up to the speaker I can hear a faint crackle.

So what are the requirements for a mobile sound file? Frequency, format, etc.

# Answer
> 4 votes
Are you using `android.media.SoundPool` or another library?

Core Media Supported formats: http://developer.android.com/guide/appendix/media-formats.html

Peter Drescher on implementing sound in Android games via FMOD: http://broadcast.oreilly.com/2011/06/fmod-for-android.html http://www.twittering.com/

He also did a presentation at the most recent AES convention in NY where he showed the equivalent implementation of FMOD vs Android for the Vector Pinball game, I don't know if he put his slides online though, can't find them anywhere.

Ogg vorbis should work fine though. Make sure you start with one encoded and formatted as a basic stereo or mono 44.1kHz Ogg Vorbis file.

---
Tags: android, sound
---


# Question
Title: Game Components, Game Managers and Object Properties
I'm trying to get my head around component based entity design.

My first step was to create various components that could be added to an object. For every component type i had a manager, which would call every component's update function, passing in things like keyboard state etc. as required.

The next thing i did was remove the object, and just have each component with an Id. So an object is defined by components having the same Ids.

Now, i'm thinking that i don't need a manager for all my components, for example i have a `SizeComponent`, which just has a `Size` property). As a result the `SizeComponent` doesn't have an update method, and the manager's update method does nothing.

My first thought was to have an `ObjectProperty` class which components could query, instead of having them as properties of components. So an object would have a number of `ObjectProperty` and `ObjectComponent`. Components would have update logic that queries the object for properties. The manager would manage calling the component's update method.

This seems like over-engineering to me, but i don't think i can get rid of the components, because i need a way for the managers to know what objects need what component logic to run (otherwise i'd just remove the component completely and push its update logic into the manager).

1. Is this (having `ObjectProperty`, `ObjectComponent` and `ComponentManager` classes) over-engineering?
2. What would be a good alternative?

# Answer
The simple answer to your first question is Yes, you are over engineering the design. The 'How far do I break things down?' question is very common when the next step is taken and the central object (usually called an Entity) is removed.

When you are breaking down the objects to such a detailed level as to have size on its own then the design has gone too far. A data value on its own is not a component. It is a built in data type and can often be called exactly what you have started calling them, a property. A property is not a component, but a component does contain properties.

So, here are a few guide lines I try and follow when developing in a component system:

* There is no spoon.
    + This is the step that you have already taken in getting rid of the central object. This removes the entire debate of what goes into the Entity object and what goes into a component as now all you have are the components.
* Components are not structures
    + If you break something down to where it just contains data then it is not a component any longer, it is just a data structure.
    + A component should contain all the functionality needed to accomplish a very specific task in a specific manner.
    + The IRenderable interface provides the generic solution to visually display anything in the game. CRenderableSprite and CRenderableModel is a component implementation of that interface that provides the specifics to render in 2D and 3D respectively.
    + IUseable is the interface for something that a player is able to interact with. CUseableItem would be the component that either fires the active gun or drinks the selected potion whereas CUseableTrigger could be where a player goes to hop into a turret or throw a lever to drop the drawbridge.

So with the guideline of components not being structures, the SizeComponent has been broken down too far. It contains only data and what defines the size of something can vary. For example, in a rendering component it could be a 1d scalar or a 2/3d vector. In a physics component it could be the bounding volume of the object. In an inventory item it could be how much space it takes up on a 2D grid.

Try and draw a good line between theory and practicality.

Hope this helps.
> 6 votes

# Answer
You already accepted an answer, but here's my stab at a CBS. I found that a generic `Component` class has some limitations, so I went with a design described by Radical Entertainment at GDC 2009, who suggested separating components into `Attributes` and `Behaviors`. ("Theory and Practice of the Game Object Component Architecture", Marcin Chady)

I explain my design decisions in a two page document. I'll just post the link since it's too long to paste it all here. It currently only covers the logic components (not the rendering and physics components as well), but it should give you an idea of what I tried to do:

http://www.pdf-archive.com/2012/01/08/entity-component-system/preview/page/1

Here's an excerpt from the document:

> ***Attributes and Behaviors in Short***
>
> `Attributes` manage one category of data and any logic they have is limited in scope. For example, `Health` might make sure that its current value is never greater than its maximum value, and it can even notify other components when the current value drops below a certain critical level, but it does not contain any more complex logic. `Attributes` are dependent on no other `Attributes` or `Behaviors`.
>
> `Behaviors` control how the entity reacts to game events, make decisions, and alter the values of `Attributes` as needed. `Behaviors` are dependent on *some* of the `Attributes`, but they cannot directly interact with each other – they only react to how `Attributes’` values are changed by the other `Behaviors` and to the events they are sent.

---

**Edit:** And here's a relationship diagram that shows how the components communicate with each other:

An implementation detail: the entity-level `EventManager` is only created if it is used. The `Entity` class just stores a pointer to an `EventManager` that is initialized only if some component requests it.

---

**Edit:** On another question I gave a similar answer to this one. You can find it here for a, perhaps, better explanation of the system:
https://gamedev.stackexchange.com/a/23759/6188
> 14 votes

# Answer
It really depends on the properties you need and where you need them. The amount of memory you will have and the processing power/type you will use. I have seen and try to do the following:

* Properties that are used by multiple components but modified only by one are stored in that component. Shape is a good example in a game where the AI system, the physics system as well as the rendering system need access to the base shape, it's a heavy property and it should remain only in one place if possible.
* Properties like position sometimes need to be duplicated. For example if you run multiple systems in parallel you want to avoid peeking across systems and will rather sync the position (copy from the master component or sync through deltas or with a collision pass if needed).
* Properties originating from controls or AI "intentions" can be stored in a dedicated system as they can be applied to the other systems without being visible from outside.
* Simple properties can become complicated. Sometimes your position will require a dedicated system if you need to share a lot of data (position, orientation, frame delta, total delta current movement, delta movement for the current frame and for the previous frame, rotation...). In that case you will have to go with the system and access the latest data from the dedicated component and you might have to change it through accumulators (deltas).
* Sometimes your properties can be stored in a raw array (double\*) and your components will simply have pointers to the arrays holding the different properties. The most obvious example is when you need massive parallel calculations (CUDA, OpenCL). So having one system to properly manage the pointers might come in handful.

These principles have their limitations. Of course you will have to push the geometry to the renderer but you will probably not want to retrieve it from there. The master geometry will be stored in the physics engine in the case where deformations occur there and synced with the renderer (from time to time depending on the distance of the objects). So in a way you will duplicate it anyway.

There are no perfect systems. And some games will be better off with a simpler system while other will require more complex synchronizations across systems.

At first make sure all properties can be accessed in a simple manner from your components so you can change the way you store the properties transparently once you start fine-tuning your systems.

There is no shame in copying some properties. If a few components need to hold a local copy it's sometimes more efficient to copy and sync rather than access an "external" value"

Also syncing doesn't have to happen every frame. Some components can be synced less frequently than others. Render component are often a good example. The ones not interacting with the players can be synced less frequently, just as the ones that are far away. Those far and outside of the camera field can be synced even less frequently.

---

When it comes to your size component it could probably be bundled within your position component:

* not all entities with a size have a physics component, areas for example, so bundling it with physics is not in your best interest.
* size will probably not matter without a position
* all objects with a position will probably have a size (that can be used for scripts, physics, AI, render...).
* the size is probably not updated every cycle but position might be.

Instead of size you could even use a size modifier, it might come in handier.

As to storing all properties in a generic property storage system... I am not sure you are going in the right direction... Focus on the properties that are core to your game and create components that bundle as many related properties as possible. As long as you abstract the access to these properties properly (through getters in the components that need them for example) you should be able to move, copy and sync them later, without breaking too much of the logics.
> 2 votes

# Answer
If components can be arbitrarily added to entities, then you need a way to query if a given component exists in an entity and to get a reference to it. So you might iterate over a list of objects derived from ObjectComponent until you find the one you want, and return it. But you would return an object of the correct type.

In C++ or C# this usually means you'd have a template method on the entity like `T GetComponent<T>()`. And once you have that reference, you know exactly what member data it holds, so just access it directly.

In something like Lua or Python you don't necessarily have an explicit type of that object, and probably don't care either. But again, you can just access the member variable and handle any exception that arises from attempting to access something that isn't there.

Querying for object properties explicitly sounds like duplicating the work that the language can do for you, either at compile time for statically-typed languages or at run time for dynamically typed ones.
> 1 votes

# Answer
> "I think, then my problem is where do i store common properties. E.g. an object as a postion, which is used by a RenderingComponent and a PhysicsComponent. Am i over-thinking the decision of where to put the property? Should i just stick it in either, then have the other query an object for the component that has the needed property?"

The thing is that RenderingComponent **uses** position, but the PhysicsComponent **provides** it. You just need a way to tell each user component which provider to use. Ideally in an agnostic way, otherwise there will be a dependency.

> "...my question is more about where those properties should go, particularly where a property is used by multiple components and no single component can be said to own it. See my 3rd and 4th comment on the question."

There is no common rule. Depends on specific property (see above).

Make a game with an ugly but component-based architecture and then refactor it.
> 1 votes

# Answer
Your gut's telling you that having the `ThingProperty`, `ThingComponent`, and `ThingManager` for every `Thing` type of component a little overkill. I think it's right.

But, you need some way to keep track of related components in terms of what systems use them, what entity they belong to, etc.

`TransformProperty` is gonna be a pretty common one. But who's in charge of it, the rendering system? The physics system? The sound system? Why would a `Transform` component even need to update itself?

The solution is to remove any sort of code from your properties outside of getters, setters, and initializers. Components are data, which is used by systems in the game to perform various tasks like rendering, AI, sound playback, movement, etc.

Read about Artemis: http://piemaster.net/2011/07/entity-component-artemis/

Look at its code and you'll see that it's based around Systems that declare their dependencies as lists of `ComponentTypes`. You write each of your `System` classes and in the constructor/init method declare what types that system depends on.

During setup for levels or whatnot, you create your entities and add components to them. Afterwards you tell that entity to report back to Artemis, and Artemis then figures out based on the composition of that entity which systems would be interested in knowing about that entity.

Then during the update phase of your loop, your `System`s now have a list of what entities to update. Now you can have granularity of components so you can devise crazy systems, build entities out of a `ModelComponent`, `TransformComponent`, `FliesLikeSupermanComponent`, and `SocketInfoComponent`, and do something weird like make a flying saucer that flies between clients connected to a multiplayer game. Okay, maybe not that, but the idea is that it keeps things decoupled and flexible.

Artemis isn't perfect, and the examples on the site are a little basic, but the separation of code and data is powerful. It's also good for your cache if you do it right. Artemis probably doesn't do it right on that front, but it's good to learn from.
> 1 votes

---
Tags: architecture, component-based, design-patterns
---


# Question
Title: Object rotating error in Bullet Physics with OpenGL
I have got some problem in my OpenGL game. I am using bullet physics and I want to achive quite simple effect - I want one object (a sphere) to roll and hit another (box) which will fall down.

I have got almost everything but still I have got some errors. When the box is hit it is rotating almost how I would like to. Well, almost means that when ball hits it it falls and rotates however there are about 20 degrees left to the ground.

It isn't stoping on a ball because the speed is so high that it is throw away and after a while it "meets" ball

This is my code for objects (including floor) initialization:

```
dynamicsWorld->setGravity(btVector3(0,-10,0));

    ballShape = new btSphereShape(1);

    fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(2,1,0)));
    btScalar mass = 5;
btVector3 fallInertia(0,0,0);
ballShape->calculateLocalInertia(mass,fallInertia);

    groundShape = new btBoxShape(btVector3(btScalar(50.),btScalar(1.),btScalar(70.)));

    btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,-1,0)));
    btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0));
btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
    dynamicsWorld->addRigidBody(groundRigidBody);

    btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,ballShape,fallInertia);
fallRigidBody = new btRigidBody(fallRigidBodyCI);
dynamicsWorld->addRigidBody(fallRigidBody);

    fallRigidBody->setLinearVelocity(btVector3(-5,0,0));

    pinShape = new btBoxShape(btVector3(0.5,2,0.5));

    btDefaultMotionState* fallMotionState2 = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,3,0)));
    btScalar mass2 = 1;
btVector3 fallInertia2(0,0,0);
pinShape->calculateLocalInertia(mass2,fallInertia2);
    btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI2(mass2,fallMotionState2,pinShape,fallInertia2);
pinRigidBody = new btRigidBody(fallRigidBodyCI2);
dynamicsWorld->addRigidBody(pinRigidBody);

```

and this is how I am setting the box position and rotation:

```
btTransform trans2;
pinRigidBody->getMotionState()->getWorldTransform(trans2);
    cubeX = trans2.getOrigin().getX();
    cubeY = trans2.getOrigin().getY();
    cubeZ = trans2.getOrigin().getZ();

    rot = trans2.getRotation();
//...
glTranslatef(cubeX,cubeY,cubeZ);
    glRotatef(rot.getX()*(360/3.14),1,0,0);
    glRotatef(rot.getY()*(360/3.14),0,1,0);
    glRotatef(rot.getZ()*(360/3.14),0,0,1);

    glScalef(0.5,5.0,0.5);
    glutSolidCube(1.0f);

```

Can someone tell me what is wrong in it? I have got no idea what else I can do.

# Answer
> 4 votes
There is an error in the code where the rotation of the box is passed to OpenGL.

`btTransform::getRotation` does not return an euler angle (like used in the code with `glRotatef`) but a quaternion.

Instead of `btTransform::getOrigin` and `btTransform::getRotation` use `btTransform::getOpenGLMatrix` and pass that matrix to OpenGL using `glMultMatrixf`.

Here is the corrected code, assuming bullet is used with single precision floating points, so `btScalar` is a `float`

```
    // get the transformation of the body into an OpenGL matrix
    btTransform trans2;
    pinRigidBody->getMotionState()->getWorldTransform(trans2);
    btScalar m[16];
    trans.getOpenGLMatrix(m);
    //...

    // pass that matrix to OpenGL and render the cube
    glPushMatrix();
    glMultMatrixf((GLfloat*)m);
    glScalef(0.5,5.0,0.5);
    glutSolidCube(1.0f);
    glPopMatrix();

```

---
Tags: c++, opengl, bullet-physics
---


title: Xna, writing XML </Asset> end element

text:
# Question
Title: Xna, writing XML </Asset> end element
got another question here. Its not about actually writing/reading files in XML, i already know how to-do this. But rather something that has bugged me for awhile. Ok, so when i write out my files, they look like this:

```
<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
 <Asset Type="ProjectWitch.Animation">
      <Filename>C:\Users\Daniel Randell\Desktop\Project Witch\Project Witch (MAIN)\Project_Witch (MAIN)\Project_Witch (MAIN)Content\player.png</Filename>
      <CurrentFrame>0</CurrentFrame>
      <Number_Of_Frames>1</Number_Of_Frames>
      <Max_Time_Per_Frame>0</Max_Time_Per_Frame>
      <Animate_Once>0</Animate_Once>
      <Using_Image>1</Using_Image>
      <Rect>
        0    166  64   58
      </Rect>
      <Vector2>
        12   12
      </Vector2>
      <Rect>
        81   71   51   59   False
        80   71   13   43   True
        121  71   12   22   True
        130  82   7    41   True
        89   63   11   23   True
      </Rect>
 </Asset Type="ProjectWitch.Animation">

```

As you can see the problem, it should write out at the end:

```
      </Asset>
 </XnaContent>

```

But it's always writes out the:

```
 </Asset Type="ProjectWitch.Animation">

```

Its a bit annoying to keep having to look into the XML files and deleting this, so i'm wondering what i'm doing wrong?

Saving Code: http://pastebin.com/yyC3q3aS

Thanks for any help :).

# Answer
You wrote:

```
writer.WriteStartElement("Asset Type=\"ProjectWitch.Animation\"");

```

That is not how you add an attribute using `XmlTextWriter`. I think the correct would be:

```
writer.WriteStartElement("Asset");
writer.WriteAttributeString("Type", "ProjectWitch.Animation");

```

And make sure you're not missing any `WriteEndElement` call.

By the way, the most recent and recommended method of handling XML in C# is the XDocument API. You should consider making the switch, because it works at an higher level, and you don't need to manually *start* and *end* your tags. Example:

```
// Create content
var root = new XElement("Player",         // Create root node
    new XAttribute("Id", "1"),            // Add attribute
    new XElement("Name", "Jon Skeet")     // Add child node with value
);

// Save to disk
XDocument document = new XDocument(root);
document.Save("file.xml");

```

Which would produce the following XML:

```
<?xml version="1.0" encoding="utf-8"?>
<Player Id="1">
    <Name>Jon Skeet</Name>
</Player>

```

---

**Edit 1**

> Just wondering though with using the XDocument API, as you can see i'm saving alot of data, more importantly the Rectangles & Vector2s. Its quite fiddly i find to save these currently and i don't want to have a new element for each field i.e X/Y/Width/Height but rather like it is currently. Is that possible using the XDocument Api?

In the comments you raised concerns about being able to do something like this:

```
  <Rect>
    81   71   51   59
    80   71   13   43
    121  71   12   22
    130  82   7    41
    89   63   11   23
  </Rect>

```

You were using methods such as `XmlTextWriter.WriteValue` and `XmlTextWriter.WriteWhiteSpace` to do this incremental sort of writing. As far as I know you can't write to an `XElement` this way, but coupled with a `StringBuilder` object (which you can reuse) it's easy to get a similar behavior:

```
var stringBuilder = new StringBuilder(); // Create only once

stringBuilder.Clear();
foreach(var r in rectangles)
{
    stringBuilder.AppendLine(
        String.Format("{0}\t{1}\t{2}\t{3}", r.X, r.Y, r.Width, r.Height)
    );
}
var rectElement = new XElement("Rect", stringBuilder.ToString());

```

The `StringBuilder` has both `Append` and `AppendLine` methods which will still allow you to construct your values similarly to what you were doing before.

But there are many other ways to do this, some more efficient, others easier. Personally, I would do:

```
public static string SerializeRectangle(Rectangle r)
{
    return String.Format("{0}\t{1}\t{2}\t{3}", r.X, r.Y, r.Width, r.Height);
}

var rectElement = new XElement("Rect", String.Join("\n", rectangles.Select(SerializeRectangle)));

```

---

**Edit 2**

> Last comment, in terms of reading the file, how would that work?

Here's a simple loading example without error handling. In a real scenario you should always check if `Element` or `Attribute` returns null:

```
var document = XDocument.Load("file.xml");
var player = document.Element("Player");
int id = int.Parse(player.Attribute("Id").Value);
string name = player.Element("Name").Value;

```

If there's more than one element with a certain name, use the `Elements` method instead to retrieve all of them at once.
> 6 votes

---
Tags: xna, c#, xml
---


title: Learning C++ for game development

text:
# Question
Title: Learning C++ for game development
I want to learn C++ for game development. Does anyone know a good way to learn this?

It can be with books, tutorials, anything. I would also like to know what is a good engine to start with?

thanks you :)

# Answer
> 3 votes
If you understand programming and just want to learn C++ then i'd recommend Thinking in C++ by Bruce Eckel, it'll teach you everything that you want to know about modern C++ in an easy to understand fashion with the emphasis on Object Oriented programming from the beginning, which is essential for creating even small games like Tetris. This book is availible for free on the author's site. However if you don't know anything about programming, then this book won't help you.

After you understand C++ there are still alot of books that'll expand your knowledge.

C++ For Game Programmers by Noel Llopis comes to mind. This books covers alot of core knowledge that any programmer will need like using inheritance, but does it in the context of games. It has alot of problem solving, information about what's under the hood, performance issues associated with using language's features and how to deal with them. Noel has his own blog, you can follow it here.

Effective C++ and More Effective C++ by Scott Meyers, two advanced books. They're more of a guidance to becomming a better programmer than an organized repository. Read them after you're comfortable with C++.

As for engines, SFML comes to mind, it's very easy to use IF you know the language.

# Answer
> 2 votes
> I want to learn C++ for game development

So you're interested in learning the *language*? Then one of these two books might be a good place to start depending on your current level.

**Beginner Level (Never used C++ / Never programmed a game)**

Beginning C++ Through Game Programming

Simple introduction to both C++ and making games. Starts from zero and introduces language features in the context of simple games. A warning though, all examples are text based and focused on the game logic, so there are no graphics covered in the book.

**Intermediate Level (Knows C++ / Doesn't know how to use it efficiently for games)**

C++ For Game Programmers

This one is excellent if you already know the basics of the language, but don't know the *tricks and best practices* of how to apply it to game programming. Once again, it's all about increasing your proficiency with *the language*, not a tutorial of how to make a game.

**Other References**

The books above are both centered *around game development*. But it's also possible to learn the language first, and only then start thinking about how to apply it to games. In that case my recommendations change into the following two books, respectively for the beginner and intermediate programmer:

* **Accelerated C++** \- Probably the best introduction to the language I've read. Teaches C++ from the ground up using practical examples and introducing you to C++ features since the start (most books start teaching C++ as if it were C).
* **Effective C++** \- The single most useful C++ book I've ever read. Teaches all about the tricks and pitfalls of the language, which you *have to know*, but most other books don't cover. This includes the two sequels written by the same author (More Effective C++ and Effective STL).

# Answer
> 0 votes
game development is not really bound to any programming language. There are certain techniques that you need to learn, wether that is in c++ or any other language is irrelevant.

Back to the point, I'm learning c++ myself right now and these tutorials are incredibly helpful for understanding the basics.

http://www.youtube.com/user/xoaxdotnet#p/c/A68C1F33757B4A38/0/WYbeLBVG34I

---
Tags: c++
---


# Question
Title: Tools for editing 2D sprite-based game levels
What are good free and widely used tools for editing 2D sprite-based game levels? I'm looking for one that allows exporting data to a custom format. One that I know of is Blender — a 3D tool, primarily, but can be used for 2D art as well — which also supports Python scripts for exporting data.

# Answer
> 6 votes
Gleed 2D is the most popular tool. It has recently been rewritten and can be found on GitHub.

The output of the tool is a simple XML file. If you're using XNA, there's a small component that'll turn the XML into an object graph. There's versions for Windows, XBox, and Windows Phone.

The new version contains lighting and behaviours:

# Answer
> 6 votes
It's been a while since the last update, but there's Gleed2D. I've used it before and it's pretty straightforward. Basically set up your layers, drag and drop sprites into the stage, and transform them into the correct place. Then export to XML and read on your game.

# Answer
> 2 votes
The best ones I know of are Mappy and tIDE. Both export in open formats, and TtDE while not as well-known also exports in its own XML format and supports Mappy FMP, and Flixel's file format, so you can move back to Mappy or easily port to Flash.

# Answer
> 1 votes
Take a look at Tiled.

---
Tags: 2d, tools, levels, map-editor
---


title: Load XNA Content Type from File

text:
# Question
Title: Load XNA Content Type from File
I'm writing my own level editor and recently got the exporter working so now I'm working on the importer. My save file structure looks essentially like this:

```
[ObjectType]
    Property=Value
    ContentProperty:ContentType=ContentName
[/ObjectType]

```

The problem is in loading the content. I'm trying to find out how to load some content with the given content type at runtime. Technically, I could do a switch-case of each type

```
switch(ContentType)
{
    case Texture2D:
        Content.Load<Texture2D>(ContentName);
        break;
    case Model:
        Content.Load<Model>(ContentName);
        break;
    ...
}

```

but that just seems messy (and I can't find a reliable listing of all of the default content types in XNA).

Is there a way for me to load the content with the proper type without having to list out all possible types?

# Answer
> 1 votes
I had a look at the code in ILSpy, and it's **heavily** generic. There isn't a private `Read(Type type)` method available.

Your option on the PC to keep things quick is to use `Expression` objects - basically compile an expression to make sure things stay quick; otherwise use reflection (which can be slower) to invoke the method.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content;
using System.Linq.Expressions;
using System.Reflection;

namespace WindowsGame1
{
    static class ContentLoader
    {
#if !XBOX
        private static readonly Dictionary<string, Func<ContentManager, string, object>> _calls = new Dictionary<string, Func<ContentManager, string, object>>(StringComparer.Ordinal);
#endif
        private static readonly MethodInfo _loadMethod = typeof(ContentManager).GetMethod("Load", BindingFlags.Public | BindingFlags.Instance);

        public static object Load(this ContentManager manager, string typeName, string assetName)
        {
#if XBOX
            var mi = _loadMethod.MakeGenericMethod(Type.GetType(typeName, true));
            return mi.Invoke(manager, new object[] { assetName });
#else
            Func<ContentManager, string, object> load;
            lock (_calls)
            {
                if (!_calls.TryGetValue(typeName, out load))
                    _calls.Add(typeName, load = CreateLoader(typeName));
            }
            return load(manager, assetName);
#endif
        }

        private static Func<ContentManager, string, object> CreateLoader(string typeName)
        {
            // Create the method info.
            var type = Type.GetType(typeName, true);
            var mi = _loadMethod.MakeGenericMethod(type);

            var paramContentManager = Expression.Parameter(typeof(ContentManager), "contentManager");
            var paramAssetName = Expression.Parameter(typeof(string), "assetName");

            // Create the call and cast-down.
            var call = Expression.Call(paramContentManager, mi, paramAssetName);
            var convert = Expression.Convert(call, typeof(object));
            var lambda = Expression.Lambda<Func<ContentManager, string, object>>(convert, paramContentManager, paramAssetName);

            return lambda.Compile();
        }
    }
}

```

Remember that most-likely you will need to use the assembly-qualified type name. So for instance:

```
var content = Content.Load("Microsoft.Xna.Framework.Graphics.SpriteFont, Microsoft.Xna.Framework.Graphics, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553", "SpriteFont1");

```

To get the AQFQN of a type simple inspect it:

```
var tn = typeof(SpriteFont).AssemblyQualifiedName;

```

# Answer
> 1 votes
If you can use Reflection on your target platform, then it's possible as follows:

```
var contentLoadMethod = typeof(ContentManager).GetMethod("Load").MakeGenericMethod(ContentType);
contentLoadMethod.Invoke(Content, new [] {ContentName});

```

---
Tags: xna, c#, assets, loading, xna-content-pipeline
---


# Question
Title: What is the state of the art at shipping game graphics such as lots of small BMP files?
We have lots of small BMP files which I think would be easier to copy if we had them combined in a big TAR/ZIP/whatever.

What is the state of the art at shipping game graphics?

We are using C# and are aware of zlib. Just brainstorming to see if there are any other solutions better than zlib.

# Answer
You could also look into SharpZipLib or DotNetZip \- DotNetZip gives you access to a `Stream` directly, which is helpful as most C# libraries out there can load from streams (as opposed to files). Furthermore DotNetZip uses the Ms-PL (BSD-Like), instead of the GPL with a legally questionable exception.

Another option is to use texture atlases \- instead of having many small images have a few big ones. These actually load slightly faster and are slightly faster at runtime if you get smart with how you draw them.

Finally you could run each asset type through the relevant lossless compressor (PNG, FLAC, etc.) and store them in a flat file (basically a zip file with compression disabled). Remember to avoid compressing compressed data, as that will *increase* the size in most cases.

Some prior art:

* MPQ: Probably as good as it gets for game assets, the lookups are designed to be fast (disk-based hash-table etc.). Each file type (that is supported) has a unique compressor.
* Quake PAK: This is basically a flat file structure.
* Doom WAD: Somewhat specific to Doom, but worth looking into.
> 7 votes

# Answer
An option is to store images in the same compression format that you use for making compressed textures. This has the advantage that you are not going to convert fro one lossy format to another, yet you store the data in a lossy format. Depending on the textures there may still be something to gain by storing such files in a compressed archive.

See this answer for a bit more info on compressed textures: https://gamedev.stackexchange.com/a/5177/3505
> 1 votes

# Answer
ZLIB could be a good answer, but if you're aware of people opening grabbing your assets, you could also make your own file format to store your assets, its not that hard though.

Here's how you can make it.

It is in C, but should not be that hard to learn, as C# is some like C and C++.

Of course, people that still have higher knowledge can catch your resources, you can add little encryption if you want, not too hard.

This can be very useful, but it will just join your files. For compression too, you have two choices.

1. **Make your entire resources file, compress it, and ship.**
This Method is easy, but not very good, you should uncompress everything if you want to take just one resource.
2. **Compress every resource, and add they compressed to the resource file.**
That's pretty good too, you'll have a slight increase in the size beside the method 1, because each file is compressed separately, but its better if you want flexibility.

Each method has its own drawbacks, you should choose wisely. Generally, if you game has a pretty low number of resources, method 1 should be better, If you have LOTS, the method 2 should fit you, because the size of all resources together will overwhelm the extra that you gain.

For compression libs, you have:

* The most famous medium, Zlib
* The one with the faster decompression, LZO
* The great compression ratio, 7-Zip

I would go with LZO if I want fast access ingame, so you have not to fear about uncompressing in real time, 7-Zip if I want the files to be shrinked A LOT or Zlib itself if I want balanced decompression ratio and size.
The choice is yours :D

Ah, of course there are others algorithms to compress data, and you can find those googling.
> 0 votes

---
Tags: c#, graphics, assets, compression
---


# Question
Title: Question About An Implementation Of Parallax Scrolling In C++/SDL/OpenGL
I been working in a project with a team for a Software Engineering class and we think that using the parallax scrolling will help our game to look really nice but we are not really sure if our idea for implementation it's the correct one, so I hope that someon will give us some guidance about our plan.

First, we have three classes, Level, Tileset, Layer, the first one has two vectors of Layers and Tilesets, so our idea is load all the data from a TMX file of the first level in a vector\>, but we only draw the part of the map that it's currently in camera, so inside a cycle we draw every layer, but we're not sure how defined a velocity for each layer so the parallax scrolling works like it supposed.

Thanks for the attention and help.

Good day....

PD: If someone need more information, don't doubt in ask.

# Answer
Parallax scrolling is just using a set of layers moving with different speed. each layer can be a tilemap, just a sprite, or anything else. normally the most front layer is a tilemap and you only check collisions and other gameplay features with that layer. just keep in mind parallax scrolling is going to simulate 3d projection using only 2d objects, so objects back in the scene should move with slower speed than those in the front.

to ease your work,, you can keep the character(player) in some fixed position. then give negate of player velocity to your parallax node. I suggest for a parallax node you only change setPosition function, in that function instead of moving parallax node itself, you have to move all it's children, respecting their depth value. for example you can use some code like this one:

```
void move(float deltaX,float deltaY)
{
    for(unsigned i=0;i<children.size();i++)
    {
        children[i]->move(deltaX / child.depth,deltaY / child.depth);
    }
}

```

all the other functions of the parallax node is same as normal node. you don't need to worry about anything else.
> 2 votes

# Answer
> we're not sure how defined a velocity for each layer so the parallax scrolling works like it supposed.

Two floats. I'd recommend one for X and one for Y, but maybe your game happens in another coordinate system.
> 0 votes

# Answer
I've implemented it simply by having the lower background layer scroll at a certain speed, and having the upper background layer scroll at half the speed of the lower background.
> 0 votes

---
Tags: c++, opengl, 2d, sdl, parallax-scrolling
---


# Question
Title: How can I make a minefield with dr racket?
Can you give me code if some knows code?it is too important for me

# Answer
You have the completely right idea by starting with something simple. However, minesweeper is a trivial program for most developers - you might try something even simpler. Maybe even start with programming something other than a game - maybe "Hello World" or such.

Try something even simpler, maybe a text adventure. This might give you the mind-set you need to make a minesweeper.

*Off topic:* People on any StackExchange website (StackOverflow included) don't take kindly *at all* to people asking for 'code'. Demonstrate your due diligence to us, and come with specific problems and we will be more than happy to help you out with any problems - but asking for an entire program will be met with a closed question and sometimes some hostility.
> 1 votes

---
Tags: c++
---


# Question
Title: Confusion with the texture coordinate system in XNA
I am creating a cow out of primitive shapes, and am using the minecraft cow texture as a placeholder. To create the primitive model I have created a 'model' class and created a sub class 'ModelCow' which inherits from the Model class. Each model contains a List of the component class which is like a sub part of the model. In the creation of the components a texturemap for each component is created, which defines the locations of each texture foreach face for that cube in a texture map for that cow.

The way each texture is determined is the top left pixel of the texture and the bottom right, I had to go through each texture and find the top left x and y and divide them by the width and height respectily - the same thing with the bottom right. The thing is the textures are all one pixel off what they should be i.e it is shifted right too far or one pixel is missing. The question is what am I doing inncorrectly. Am I meant to start counting from zero when I get the x and y/ top and right coordinates for the texture. Also in this case the actual width and height of the texture and subtracted by one, i.e. 32 is 31 and 64 is 63

Example of what I am doing is:

AAAAAAAA

AAAAAAAA

A#AAAAAA

AAAAAAAA

the '#' would be 1, 2 and the width would be 7 and the height would be 3. Is this correct?

Here is the code:

```
    float width = 63f;
    float height = 31f;

    // Body
    TextureMap bodyMap = new TextureMap();
    bodyMap.Add(new Vector4(28f / width, 4f / height, 39f / width, 13f / height), FaceDirection.ZIncreasing);
    bodyMap.Add(new Vector4(40f / width, 4f / height, 51f / width, 13f / height), FaceDirection.ZDecreasing);
    bodyMap.Add(new Vector4(18f / width, 14f / height, 27f / width, 31f / height), FaceDirection.XDecreasing);
    bodyMap.Add(new Vector4(28f / width, 14f / height, 39f / width, 31f / height), FaceDirection.YDecreasing);
    bodyMap.Add(new Vector4(40f / width, 14f / height, 51f / width, 31f / height), FaceDirection.XIncreasing);
    bodyMap.Add(new Vector4(52f / width, 14f / height, 61f / width, 31f / height), FaceDirection.YIncreasing);
    components.Add(Shape.BuildCube(new Vector3(0, 0, 0), new Vector3(0.7f, 0.7875f, 1.30f), bodyMap));

```

Whereas the first two coordinates are the top left and the last two are the bottom right. X and Y respectively.

# Answer
The way to think about texture coordinates (UVs) is not as indices into a 2D array of texels but as defining distances in a Cartesian coordinate system. In other words, integer values (before dividing by width or height) refer to the *edges between* pixels, not the pixels themselves. If the origin is at the upper left, then the coordinates look like this:

So the width and height are 8, not 7; and the coordinates of the blue rectangle are (1/8, 3/8) and (5/8, 7/8).
> 3 votes

---
Tags: xna, textures, coordinates
---


# Question
Title: Process for developing psd images into animation
I wrote a kids' picture book that I want to make into an iPad app and iPhone app.

(More of a story than a game, but same principles, I guess.)

Here's a sample page: https://img.skitch.com/20120108-bqusir4xt3hhxx5fufhh7pw4wy.jpg

(There are words on each page -- I've just scrubbed them out on the image for this example.)

All the images are in Photoshop.

I want to make an app of the book for iPads and other tablets.

For the app, I'd like to add a little animation on each page. Things like fish changing their expressions. Some interaction. Fish swimming on some pages, and other stuff.

I want to know who I should recruit to do the animation:

The illustrator who did the original images normally doesn't do animation.

1. Since that illustrator doesn't normally do animation, I guess I need to get an animator on board for the project -- what skills am I looking for in that person?

(Obviously they need to know how to make an animation, but what technology etc will they need to know?)

1. To draw the different frames for the animation, would I need to employ the same illustrator who did the original images, or would a good illustrator be able to do that, based on the images that already exist?

(The illustrator who did the original images is available, but I'd need to wait a while for her to be able to fit the job in.)

1. The images don't exist as vector files -- they are Photoshop bitmap. Is this an issue?

Thanks, Richard

# Answer
**TL;DR**

> what skills am I looking for in that person?

Depends on the extent of the animations you need. Read the rest of the post for more info on that.

> To draw the different frames for the animation, would I need to employ the same illustrator who did the original images, or would a good illustrator be able to do that, based on the images that already exist?

I've met a few artists who were very capable at mimicking other artist's styles, so I'd say a good illustrator *might* be able to do that. You'll need to ask them directly.

> The images don't exist as vector files -- they are Photoshop bitmap. Is this an issue?

I don't think so, the image you showed is digitally painted so I can't imagine a vector format even being useful here. The resolution of photoshop files and their separation in layers are more important in this case.

**Long Story**

I think each artist usually has a different workflow that they're used to (for instance, check this video of Dan Paladin animating one of the boss characters from The Behemoth's hit, Castle Crashers) so most advice I can give will depend a lot on the actual illustrator.

For starters, what type of animation are you really looking to have? Do you want fully animated characters (e.g. Disney style) or you just want some pieces of the image to move, and small parts of the images to change? For the first approach, you'd obviously need someone who is very talented and capable of adapting your old illustrator's style. For the second approach, most decent illustrators should be capable of handling it. Provide that sort of info when looking for the illustrator, and show the assets you already have.

Whether the images not being in vector format is an issue or not, that depends on the workflow of your illustrator. Some are more used to working in vector format, while others use a more traditional painting method. But looking at your image, I don't see how it could be vector anyway, so you'll probably want someone who's more into digital painting. Either way, it helps if your source images have an high quality / resolution.

It would also be very helpful if your source images are separated into layers, so that portions can be edited at a time without affecting the rest of the picture. If the images are not separated into layers, your new illustrator will need to be skilled enough to *repaint* over the old picture.

The bottom line I think is that you will need to discuss your requirements over with each candidate, making sure to show them everything that you currently have and what you seek, and they should be able to tell you what their capabilities are.
> 2 votes

---
Tags: animation
---


# Question
Title: Which of these DirectX11 calls actually sends data to the GPU?
I'm trying to learn graphics programming and DirectX11.

I'm trying to learn how to minimize CPU-GPU transfer and graphics programming in general.
I have a question that I have been unable to answer myself from online resources:

Which of the D3D methods actually sends the data to the GPU(and, equivalently, for a static mesh does ALL the vertex data get passed to the GPU every frame, or only once)?

Code follows:
(simplified for stackexchange)

In my "mesh" class, I have a vertex buffer:

```
ID3D11Buffer *m_pVBuffer;

```

In my mesh's constructor, I set some vertices to the vertex buffer:

```
D3D11_MAPPED_SUBRESOURCE ms;
devcon->Map(m_pVBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms);
memcpy(ms.pData, &vertices[0], sizeof(VERTEX) * vertices.size());
devcon->Unmap(m_pVBuffer, NULL);

```

Then in my mesh's "render" method, I do this:

```
UINT stride = sizeof(VERTEX);
UINT offset = 0;
devcon->IASetVertexBuffers(0, 1, &m_pVBuffer, &stride, &offset);
devcon->IASetIndexBuffer(m_pIBuffer, DXGI_FORMAT_R32_UINT, 0);
devcon->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
devcon->DrawIndexed(m_num_indices, 0, 0);

```

To repeat: Is the data uploaded to the GPU when I Map, memcpy and Unmap the vertex buffer, or is it uploaded every frame, when I call IASetVertexBuffers?

# Answer
This is a tricky question because you don't have complete control over whether a vertex buffer is stored in VRAM or main RAM. The driver makes that decision for you based on the usage and CPU access flags specified when you create the vertex buffer.

Generally speaking, buffers with default and immutable usage will be stored in VRAM; those with staging usage will be stored in main RAM; and those with dynamic usage could be in either place. However, if insufficient VRAM is available the driver will store resources in main RAM as a fallback.

If a buffer ends up in VRAM, data goes across the system bus (that connects the CPU and GPU) whenever the CPU updates the buffer (that is, when you do a Map/Unmap pair). If it's in main RAM, the GPU will read the data across the system bus every time you use that buffer for rendering.

So, typically, for static meshes you would use immutable usage and the buffer would be stored in VRAM, so there is no additional system bus transfer after the initial setup. For a dynamic vertex buffer (for particles or similar) you'd use dynamic usage, and the data would go across the bus once each frame - if it's in VRAM, the bus will be used for the CPU to write to it, and if it's in main RAM, the bus will be used for the GPU to read it.
> 7 votes

# Answer
The answer will be dependent on what any particular generation of highly optimized hardware driver feels like doing, which is to say that there is no general answer for you.

Add to that complication the fact that drivers are rendering 1-N frames behind of what you're currently telling them to render because 3D cards are both highly serialized and parallel and cached and work asynchronously to get things done.

If you're just learning then the important information to know is the sequence points to preparing a render: describe the data, copy in the data, tell the driver what data to use, then fire off the render. And not what happens when, that is a very deep rabbit hole indeed.
> 0 votes

# Answer
My understanding, mostly based on reading this is that the driver generally won't send any resources across to video memory, until the resource is used in a draw call.

That would mean the constructor probably won't touch the GPU hardware at all, and the render method will. However even the DrawIndexed() call probably won't make it to the hardware immediately because it's more CPU efficient to buffer up large lists of GPU commands.

The driver can also unload data from GPU memory when it runs out (assuming it has a copy of it in main RAM). In extreme cases this can happen more than once per frame.

Of course all of this is hidden from the programmer by the driver, so you can't rely on it being like that - drivers change all the time.
> 0 votes

---
Tags: directx, directx11, gpu
---