title: Optimizing hierarchical transform

text:
# Question
Title: Optimizing hierarchical transform
I'm transforming objects in 3D space by transforming each vector with the object's 4x4 transform matrix. In order to achieve hierarchical transform, I transform the child by its own matrix, and then the child by the parent matrix. This becomes costly because objects deeper in the display tree have to be transformed by all the parent objects.

Is there a faster way to transform vertices to achieve hierarchical transform?

# Answer
> 7 votes
Quite a common thing to do with some matrices is to cache the value and only update it when it's changed. There's two ways to manage this scheme, push or pull.

Pushing matrices would involve, at the point of a matrix changing, letting child nodes know that the matrix has changed. These nodes will then have to let their children know, and so on. The upside is that it only requires storing the extra matrix, but you re-compute it every time it changes - if you change matrices within the hierarchy a lot then the matrices at the bottom will change an awful lot during the frame.

The reverse it to pull matrix changes - when a value is changed, it sets a boolean value which says that the matrix has changed since it was last read. This is commonly referred to as a dirty matrix (programmers are weird.)

Upon requiring a matrix, you check if it is dirty (or its parents). If it is, you recalculate the matrix. The downside of this is that you need to check if things are dirty all the time.

When I said there was only two methods, I lied: you can go for a hybrid approach somewhere in the middle. Push the dirty flag down the tree, and let children know that at least one of the parents' matrices are dirty. At the same time, calculate the matrix only when needed. If your only ever process the tree in a downward fashion (from the root to the leaves) then you can get away with only one matrix multiplication per node as a maximum.

---
Tags: 3d, mathematics, performance, matrix, transformation
---


# Question
Title: getting bone base and tip positions from a transform matrix?
I need this for a Blender3d script, but you don't really need to know Blender to answer this.

I need to get bone head and tip positions from a transform matrix read from a file. The position of base is the location part of the matrix, length of the bone (distance from base to tip) is the scale, position of the tip is calculated from the scale (distance from bone base) and rotation part of the matrix.

So how to calculate these?

```
bone.base([x,y,z]) # x,y,z - floats
bone.tip([x,y,z])

```

# Answer
You can find the base by multiplying the origin vector (0, 0, 0) by the transform matrix.

The tip question is slightly more in-depth: it really depends on what the canonical direction is that all the bones are defined from - in other words, where does the bone originally rotate from?

One way or another, to get the tip position you multiply a unit vector (for example, in Z this would be (0, 0, 1)) by the transformation matrix.

Bear in mind as well that your bones are probably hierarchical and the position will be relative to its parent joint - you will need to multiply one particular joint's matrix by its parent (and the parent joint by its parent, and so on) to get a global, world position.
> 1 votes

# Answer
If you want to preserve the original transform so that Blender's bones recreate the same transform, you will also need to calculate the bone roll.

Blender has a function to calculate the bone head, tail and roll from a transform matrix in C code. I haven't found a convenient way to access this functionality from the Python API, but fortunately the functions are short and can easily be translated into Python.

Below is a direct translation of the functions you need, for Blender 2.62 or later:

```
def vec_roll_to_mat3(vec, roll):
    target = Vector((0,1,0))
    nor = vec.normalized()
    axis = target.cross(nor)
    if axis.dot(axis) > 0.000001:
        axis.normalize()
        theta = target.angle(nor)
        bMatrix = Matrix.Rotation(theta, 3, axis)
    else:
        updown = 1 if target.dot(nor) > 0 else -1
        bMatrix = Matrix.Scale(updown, 3)
    rMatrix = Matrix.Rotation(roll, 3, nor)
    mat = rMatrix * bMatrix
    return mat

def mat3_to_vec_roll(mat):
    vec = mat.col[1]
    vecmat = vec_roll_to_mat3(mat.col[1], 0)
    vecmatinv = vecmat.inverted()
    rollmat = vecmatinv * mat
    roll = math.atan2(rollmat[0][2], rollmat[2][2])
    return vec, roll

pos = transform.to_translation()
axis, roll = mat3_to_vec_roll(transform.to_3x3())

bone.head = pos
bone.tail = pos + axis
bone.roll = roll

```
> 0 votes

---
Tags: 3d, matrix, blender, transformation
---


# Question
Title: Help to understand directions of sprites in XNA
If I want to move a sprite to the right and upwards in a 45 degree angle I use

```
 Vector2 direction = new Vector2(1,-1);

```

And if the sprite should move straight to right

```
 Vector2 direction = new Vector2(1,0);

```

But how would I do if I want another directions, lets say somewhere between this values? I have tested with some other values, but then the sprite either moves to fast and or in another direction than I expected!? I suspect it's about normalize!? Another thing I have problem with to understand.

I'm doing a simple asteroids game as a task in a class in C# and XNA. When the asteroids hit the window borders, I want them to bounce back in a random direction, but I can't do this before I understand how directions and Vector2 works. Help is preciated! Thanks!

# Answer
You'll find that your first value is moving about 1.4 times as fast as the second, based on the lengths of the vectors:

```
length = sqrt( x*x + y*y )
sqrt( 1*1 + -1*-1 ) = 1.414...
sqrt( 1*1 + 0*0 ) = 1

```

And you're right, it's about normalizing values. All normalizing does is make the length of that vector 1 unit long - hence it's called a **unit vector**. On the plus side, normalizing is simple! Either languages have it build in and you can just do:

```
Vector2 dirNormalized = direction.Normalize();

```

Or, you can do it manually by dividing each component by the length:

```
float length = sqrt( direction.X*direction.X + direction.Y*direction.Y )
Vector2 dirNormalized = new Vector2( direction.X / length, direction.Y / length );

```

I would use the built-in methods. Much less hassle. ;)

If you want to specify directions at arbitrary angles, the easiest way to do this is using trigonometry:

```
Vector2 direction = new Vector2();
direction.X = Math.Cos( angleInRadians );
direction.Y = Math.Sin( angleInRadians );

```

This will give you a unit vector in the direction of `angleInRadians` from your left example, going counter-clockwise. If this sounds complicated, think of it as a clock hand that starts at 3 and goes counter-clockwise as the angle increases, and reaches back to 3 at 2\*PI radians, or 360 degrees.

To get extra-fancy, multiply these by a 'speed' value to get a velocity vector:

```
float speed = 8.5f;
direction.X = speed * Math.Cos( angleInRadians );
direction.Y = speed * Math.Sin( angleInRadians );

```

This will give you a vector of length 8.5, with the direction specified by the angle.
> 5 votes

# Answer
If you want a vector pointing a random direction in 2D, generate a random angle between 0 and 2pi, and calculate the vector (cos(angle), sin(angle)). This is already normalized (it has length of one unit), so you can multiply it by the desired speed of the asteroid to get the velocity vector.
> 0 votes

---
Tags: xna
---


title: how does HDR work?

text:
# Question
Title: how does HDR work?
I'm trying to understand what HDR is and how it works.

I understand the basic concepts and have an slight idea of how it is implemented with D3D/hlsl.

However it's still pretty foggy.

Say I'm rendering a sphere with a texture of the earth and a small point list of vertices to act as stars, how would I render this in HDR ?

Here are a few things I'm confused about:

* I'm guessing, I can't use just any basic image format for the texture as the values would be limited to \[0, 255\] and clamped to \[0, 1\] in a shader. Same goes for the back buffer, I take it the format needs to be a float point format ?
* What are the other steps involved ? Surely there has to be more than just using floating point formats to render to a render target and then apply some bloom as a post process ? (considering the output will be 8bpp anyway)

Basically, what are the steps for HDR ? How does it work ? I can't seem to find any good papers / articles that describe the process, other than this one, but it seems to skim over the basics a little, so it's confusing.

# Answer
> 19 votes
HDR techniques allows you to simulate a greater range of detail than you can view on screen than with traditional lighting/textures. You can compare it to how the eye behaves when exposed to different amounts of light - when there's too much light the eye lets less light in so things are still in your visible range. When there is not enough light, the iris opens more so more details can be seen.

The right hand side of this image is using HDR. It makes more use of the range of colors, the darks are darker and the bright areas are brighter. In comparison the left hand side of the image looks a little flat.

The basic steps are:

1. Render your scene to floating point texture (with a format such as A16B16G16R16F) using other floating point textures on your models, and/or lights that may have a brightness greater than 1.0f.
2. To display this texture the range of visible colors needs to be converted to something displayable on your screen - this process is called tone mapping, and a variety of different tone mapping equations can be used to get different effects. This is a must since monitors can't display the full range of colors or luminescence that we can store in floating point textures (it would be cool if it was possible, but it would also be a blinding hazard...).
3. Bloom and other after effects are added to further exaggerate the difference in luminescence of the things rendered. The bloom is calculated from the floating point buffer and combined with the tone mapped image.

*Hope that helps*

# Answer
> 7 votes
Technically, HDR merely means using a larger range of possible values for your graphics. Usually you're restricted to 256 discrete values for the red, green, and blue channels, which means that if you have 2 items, one twice as bright as the other, and a 3rd which is 10,000 times brighter than the first, there's no way you can represent all 3 in the same scene correctly - you either make the bright object only 256x brighter than the first instead, or you make both the dull objects completely black (losing the contrast between them) and then the bright object is infinitely brighter than them both.

This is easy to fix by using floating point values for the red/green/blue values - but now you have the problem of how to display that on a graphics device that only handles a fixed number of discrete values per channel (eg. 256). So the second part of the problem is how to map your floating point values back to the limited range. The trivial solution is to scale all the values proportionately into the discrete range, but this would mean that 1 very bright pixel could make the rest of the screen black, etc. Sometimes this is what you want, sometimes it's not - see CiscoIPPhone's tone mapping link for examples of how you can approach this.

It's generally not your textures that need to be stored in a new format - it's when the lighting is applied to them that you need to be able to accommodate larger values. Obviously however if you have light sources baked into a texture - eg. a starry background - you might want a higher resolution format there. Or just have the shader scale the values of such materials up when the time comes to render them.

# Answer
> 5 votes
Computers traditionally represented each pixel on screen as only 24 bits in memory: 8 for red, 8 for green, and 8 for blue. This is almost enough bits that a human wouldn't notice if you added more, and the 8-bit byte is very convenient for microprocessors, so that's what stuck.

While 8 bits is almost enough precision to *display* an image, it is definitely not enough precision to *compute* an image. At various points while computing an image, at least 32 bits of precision is required.

This is why pixel shaders compute colors in 32-bit precision, even when you are rendering to an 8-bit precision image. Otherwise, you couldn't for example divide a value by 1000, and then later multiply it by 1000, because dividing *any* 8-bit value by 1000 results in zero.

There has been a trend in realtime 3D graphics toward keeping all graphics in \>8 bit precision until the last possible moment, at which time the \>8 bits of red are downsampled to 8 bits, and so forth for green and blue.

HDR refers to the act of rendering to images which have higher than 8-bit precision. In contemporary TV videogames, 16-bit precision is the norm, and this may be "enough" in videogames for years to come.

# Answer
> 2 votes
One aspect of which I think is key for HDR is the correct application of monitor gamma.

The monitor you are looking at produces light as a function of the input pixels. You might expect that a pixel with value 255 will produce (approximately) 255 times more light than a pixel with value 1. This is not the case. With a standard monitor gamma of 2.3, it is 255 ^ 2.3 times brighter, or about 340000!

Everybody producing content (camera manifacturers) knows this, or (if you're a designer) you implicitly compensate for it.

This is all fine if you just render bitmaps (well, most of the time), but if you use them as textures in a 3D scene it is a different story. If you want to model interaction with light correctly, you should use linear light calculations throughout the rendering pipeline. This means

* correcting your textures for gamma
* render everything with linear light (where you need lots of precision due to the High Dynamic Range of light),
* apply the inverse gamma transform of the monitor as the last thing before you put the image on screen.

When you make this change to an existing scene, with existing artwork, lights, etc, you probably have to fix a lot of your light intensities and textures, because they were chosen to look nice when rendering with non-linear light. So it is not a feature you can just "turn on" and expect everything to look better just like that.

---
Tags: c++, hlsl, directx11, hdr
---


title: 3D Texture Mapping (Atlas)

text:
# Question
Title: 3D Texture Mapping (Atlas)
This is a pretty simple question. If I was to use multiple images in a single texture for a 3D cube, how would I go about re-using each vertex (having 8 total vs 24)?

With a single buffer of 8 vertices, I don't see how I'd properly reuse the UV values.

Any help on that? I know it's not terribly clear, but I figured it was a simple question.

The 2D method is pretty easy, the next coordinates would be the same as the first (0,0 and 0,1 respectively).

However, the above 3D version has me quite befuddled.

# Answer
> 3 votes
Just duplicate the vertices. Sharing vertices is generally for when you have “smooth” surfaces with attributes that are continuous across the adjacent edges, not sharp edges like those of a cube. It is quite typical to use duplicated vertices when drawing cubes.

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


# Question
Title: Is it possible to load shader files from a DLL?
I have a few HLSL files that I'd like to add into a DLL project so that I don't have to keep adding these same shader files into a new Content project every time I want to use them. Is this possible, or does the XNA framework have to compile the shader files beforehand?

# Answer
> 3 votes
I have another solution in addition to Russell's which allows you to use the content manager and allows you to embed all of the types of content XNA supports.

XNA supports the ContentManager though a resource instead of a content project. To use it do the below. Of course you will need to pass a reference of your game's services at some point.

```
ResourceContentManager Content = new ResourceContentManager(game.Services, Resource1.ResourceManager);

```

Use this to compile the shader or anything to a xnb.

Add any and all of the XNB to your resources. Them simply load your content as usual.

```
Content.Load<Texture2D>(".\\assetName")

```

# Answer
> 5 votes
You don't actually need to have an actual content project: all you need to do is copy the effect XNBs to your output directories.

However, if you really want to embed them in a DLL first create a .resx in your DLL and add all the compiled effects to it (you can use `fxc` to make these - which can be found in the DirectX SDK, it's also available in the Content Pipeline API). At runtime use the byte array effect constructor to create effect from the resources. For example:

```
new Effect(GraphicsDevice, MyEffectResources.Blur, CompilerOptions.None, null);

```

Or for XNA 4.0:

```
new Effect(GraphicsDevice, MyEffectResources.Blur);

```

Keep in mind that you won't get the resource sharing that `ContentManager` does: you will have to roll your own mechanism to ensure that you only instantiate the effects once (e.g. a `static Dictionary<string, Effect>`).

# Answer
> 1 votes
I used the Stock Effects Sample to do just this, which also allows you to create a wrapper class that works like the standard effects.

There is a readme inside the sample download that explains exactly what to do. The sample contains a project that compiles shaders to a binary using the EffectProcessor class. You add the shader and subclass Effect in your library, build the binary and add it as a resource. Your Effect subclass then passes the binary into the Effect constructor.

So I just reference the library from my game project and go `var effect = new AwesomeEffect()`

---
Tags: xna, shaders
---


title: Game getting progressively laggier?

text:
# Question
Title: Game getting progressively laggier?
I have a small game in HTML5 that uses socket.io to communicate with a node.js server. Now my problem is that, ever since I did my last update on it it seems to have something "chunk up" in the background making it laggier and laggier the longer it runs. In the update were a few temporary local variables being defined with var(you know, variables that are only used during one function and then not needed anymore) alongside with a lot of other changes. The update actually featured a new jumping system that allowed players to jump higher when holding down the jump button, and that's it. I am not even sure if this update or something else is causing this. Might the "var" have caused it? Or what other reasons might this strange complication have?

EDIT: Some stuff that I think might be the reason for this and some details:

* Temporary variables defined with var.
* I prerender some graphics in the background, however that only happens once, and that's when the game starts.
* The map is infinite, being generated on as you move through it. When it then receives a chunk from the server it keeps that chunk stored in the client, however it also seems to get laggier and laggier even when you stay in the same chunk, not loading any new chunks from the server.
* It has a chat which basically puts a new piece of text into a div every time it receives a message, however it also got progressively laggier when I was alone on the server(in other words: I received no chat messages)

# Answer
As Jonathan said, this is purely speculation. When I heard about "things getting laggier and laggier" the first thing that came to mind was a memory leak. I don't know how applicable this may be to your specific application, but my guess is that it is some sort of data leakage - data not being cleared when it should be.
> 3 votes

# Answer
This is something you simply have to test:

1. Find a working revision.

* Start by reverting your version to the one before the update or the one where the roblem doesn't appear (you're using version control right, then this is very easy) and verify that the earlier version of the code doesn't have this problem.
    * **Never assume anything, always verify**
2. Pin-point the revision to blame

* Once verified, go through the versions until you find the one where the issue appears. If you as you say, have only one new version, that one is likely to blame. If not and it's hard to guess which revision caused the issue, use a binary search approach ^^
3. Find the code-change in the blamed revision to blame

* Revert to the previous version and start adding the changes from the next version again, one by one, until the problem appears again. Either do it file by file, function by function or in any other suitable chunks you can think of that still runs.

Once you find the file or chunk you can then narrow it down to a function or in some cases a single line of code.

Now figure out why that part of the code causes the problem and fix it - it could be a memory leak or thousands of other things, but it's almost impossible to guess without homing in on where the issue appeared.

And then **post that part of the code** ^^
> 2 votes

# Answer
Another wild guess: perhaps you are not removing objects correctly and your collision detection gets out of control. Brute force collision detection scales very poorly.
> 1 votes

---
Tags: javascript, html5, lag
---


# Question
Title: Split vector vs matrix notation for transformation
Some rendering engines like Ogre prefer to use a individual vector based notation for transformations like the following

Split vector notation: Net Transformation is represented by Scale vector = sx, sy, sz

Transformation vector = tx, ty, tz

Rotation Quaternion Vector = w,x,y,z

Matrix notation: There are other engines which simply use a net combined transformation matrix.

What are the advantages of the first notation over the second?

Also for animation interpolation does it work in the first notation that we interpolate across the individual components and use the interpolated parts to get the net transformation? Is this another advantage?

# Answer
> 1 votes
The combined matrix requires decomposition to get the individual elements. E.g., if you want to ask "what is this object's scale, and if it's below 1, double it," then storing everything as a matrix only complicates matters. Storing the individual components makes it trivial to efficiently alter the transform, and the recompute the matrix later when necessary.

Animation is one area where this matters. If you want to interpolate between two positions while applying a constant rotation, you will need the decomposed matrix (the individual translation and rotation components) to do it correctly.

---
Tags: opengl, 3d, graphics, ogre
---


# Question
Title: how does server communication work in a flash game with a php backend
I am trying to create a browser game using actionscript/flash. Currently, I'm trying to understand how I would go about creating a back-end which interfaced with my MySQL database.

As far as I understand, If I create a php file on a webserver called test.php and then navigate to a webpage hosted on the server eg. www.example.com/test, the php script will run and display the result in my browser.

This would use http. Is this how communication between client and server usually works in a flash game? for example, if the game needed to query the db. Would actionscript have to essentially invoke the url of the php script that would execute the query? it could then parse the data and use it.

If this is the case, then is JSON considered a good way to transfer data over http?

# Answer
> 2 votes
There are two primary approaches. If your game's needs on the server infrequent (storing high scores, loading account info, etc.) then you can simply make HTTP calls from Flash to your PHP scripts. Flash can send variables to the script using standard means and then parse some output format you print from the PHP script (XML, JSON, whatever).

If your game requires more real-time or server-push data, like chat, multiplayer features, etc, ten you may want to use Flash's networking API, such as the Socket or XMLSocket classes. Interfacing these properly with a server is a bit more difficult; PHP is not at all an ideal language to use for such things due to its HTTP-oriented internals (it is designed to run for short scripts servicing a single request, not long-running event- driven multiplexed IO server processes). At risk of sounding like a brogrammer, you might want to give NodeJS a look, particularly the popular socket library Socket.io.

If you're unsure which you want, you probably want the first one. It is much easier to deal with and is likely closer to your skill level. Move on to the more advanced networking approach only if you really need it, and only after you have a solid understanding of the simpler model.

---
Tags: server, php, actionscript
---


# Question
Title: Question about Target parameter of Matrix.CreateLookAt
I have a newbie question that's causing me a little bit of confusion when experimenting with cameras and reading other peoples implementations - does this parameter represent a point or a vector?

In some examples I've seen people treat it like a specific point they are looking at (eg a position in the world), other times I see people caching the orientation of the camera in a rotation matrix and simply using the Matrix.Forward property as the "target", and other times it's a vector that's the result of targetPos - camPos and also I saw a camPos + orientation.Forward

I was also just playing around with hard-coded target positions with same direction eg 1 to 10000 with no discernible difference in what I saw in the scene.

Is the "Target" parameter actually a position or a direction (irrespective of magnitude)? Are there any subtle differences in behaviors, common mistakes or gotchas that are associated with what values you provide, or HOW you provide this paramter? Are all the methods I mentioned above equivalent? (sorry, I've only recently started and my math is still catching up)

# Answer
> 0 votes
**Position and Target are point locations** in space. The UP part is a normalized direction vector to indicate which way is up for when the matrix is built. All variants of those parameters being passed in are data tricks used to make what the engine is using match up to what the function wants to see.

For example = for a camera at origin the orientation forward could be used as the Target point directly with the camera's Position being 0,0,0.

camPos + orientation Forward gets the same result, only it factors in that the camera may not be at 0,0,0 and so it's more general in use.

The "magnitude" of where the source and target points are in space doesn't matter (outside of floating point precision), as you've noticed a change of 1-\>10 from Position-\>Target is the same as a change of 1-\>1\_million.

Finally, all the different ways of creating the source and target points are equivalent within the limits of floating point precision.

---
Tags: xna, mathematics, xna-4.0
---


# Question
Title: How many localisations are too much for a game?
We are making an RTS game and we intend to add localizations to all languages our players use. So far we have 16 locales and about 3-4 are being planned.

Now some crazy ideas pop up from our community, players ask for "funny text" localizations. We have been already offered a pack that makes it for 1 of our languages. Now I was thinking where should we draw a line between official localizations which we include into the game and unofficial mods that players will have to install on their own?

Obviously overcrowding locale selection menu with all sorts of funny locales (LOL-cat, redneck, welsh, medieval, simplified, etc.) for all the languages seems way too much. But is it really? What are the hidden pros and cons of having too much locales and how much is too much?

# Answer
> 3 votes
You can always sub-divide your menus into the real language locales and the modified, funny ones. Most software is split between built-in menu items and an "add-ons" section so it won't feel out of place for your players, I'm sure.

If these text variants are easy and cheap to produce then consider using them as marketing, release one every N weeks to give you an excuse to send out emails that remind people about your game and something new for it.

Even if you could turn out 100 overnight I would still release them at a slow pace. Anything that your players get too much of too fast will cheapen the impact, instead of feeling good "oh look at this neat thing the devs did for us" it quickly becomes "oh look at all this crap the devs throw at us."

In the end it's kind of a touchy feely answer since I don't have any good numbers; you want just enough so the menu option for it doesn't look barren and not so many that you have to scroll around endlessly just to find something.

In any case, it's a game and funny locales are... funny =) Is it possible to have too much fun?

# Answer
> 0 votes
It really depends on the style of your game (or the style you wish to convey). The only game where I have seen this kind of localization is the Worms series. It was a really funny feature, which added so much to the fun factor of the game. However, it might not have been so without the excellent voice acting.

Localization can be a tremendous amount of work if you have lots of text. You must think about the value it adds, and compare it to the effort it takes. How many people are going to play with the Welsh settings, if you have no voice acting? A hundred? Are you gonna lose those players if you don't have a Welsh version?

It seems that you already have a nice, constructive community. I think you should just provide them a way to make their own localization packs. Make it really easy (like an XML file), and your community will do it.

# Answer
> 0 votes
Here's an excellent article about localization:

http://www.altdevblogaday.com/2012/06/27/localization-pipeline/

If you don't want to clutter your menu's with unnecessary localizations, hide them. Put them deep in the settings menu so they won't bother regular players.

But if your localization is defined in external files (like an XML file), it doesn't really matter, because then players can add any localization they like as long as it parses correctly.

---
Tags: localization
---


# Question
Title: Boolean checks with a single quadtree, or multiple quadtrees?
I'm currently developing a 2D sidescrolling shooter game for PC (think metroidvania but with a lot more happening at once). Using XNA.

I'm utilising quadtrees for my spatial partitioning system.

All objects will be encompassed by standard bounding geometry (box or sphere) with possible pixel-perfect collision detection implemented after geometry collision (depends on how optimised I can get it).

These are my collision scenarios, with \<\> representing object overlap (multiplayer co-op is the reason for the player\<\>player scenario):

```
Collision scenarios (true = collision occurs):
Player              <>      Player          =   false
Enemy               <>      Enemy           =   false
Player              <>      Enemy           =   true
PlayerBullet        <>      Enemy           =   true
PlayerBullet        <>      Player          =   false
PlayerBullet        <>      EnemyBullet     =   true
PlayerBullet        <>      PlayerBullet    =   false
EnemyBullet         <>      Player          =   true
EnemyBullet         <>      Enemy           =   false
EnemyBullet         <>      EnemyBullet     =   false
Player              <>      Environment     =   true
Enemy               <>      Environment     =   true
PlayerBullet        <>      Environment     =   true
EnemyBullet         <>      Environment     =   true

```

Going off this information and the fact that were will likely be several hundred objects rendering on-screen at any given time, my question is as follows:

**Which method is likely to be the most efficient/optimised and why:**

1. Using a **single quadtree** with boolean checks for collision between the different types of objects.
2. Using **three quadtrees** at once (player, enemy, environment), only testing the player and enemy trees against each other while testing both the player and enemy trees against the environment tree.

# Answer
I have recently implemented a similar scenario in my game. I have the same principles (e.g. no friendly fire etc.), and this is how I've done it:

1 . All objects (even Environment) have a PlayerID property. In your game, for example: Environment.PlayerID = 0, Player.PlayerID = 1, Enemy.PlayerID = 2 etc. If a bullet is fired by the player: Bullet.PlayerID = 1, and so on.

2 . The first step in my collision detection is to check if the two objects I test for collision are actually the same. The second step is to see if their PlayerID's are the same:

```
    if (obj1.PlayerID != obj2.PlayerID){ ... }
    else { continue; }

```

This already narrows down the cases, but I added some further optimizations:

3 . I have a Collision class:

```
  public class Collision{
     public Object Victim;
     public List<Object> Colliders = new List<Object>();
  }

```

In my collision detection loop, I make a new Collision instance for each object in my scene that happen to participate in a collision. For example, if obj1 collides with obj2, I will create two new Collisions so:

```
  Collision coll1= new Collision();
  coll1.Victim = obj1;
  coll1.Colliders.Add(obj2);
  Collision coll2= new Collision();
  coll2.Victim = obj2;
  coll2.Colliders.Add(obj1);

```

If I detect another collision for obj1 in the same Update cycle (with obj3 for example), I just add the obj3 to the coll1.Colliders list, and create a new Collision for obj3 (unless one already exists).

4 . Once I went through all the objects in the scene, I have a nice list of Collisions. Now I can go through that list, and apply the collision effects to their "Victims".

5 . I handle the collision effects in the Player, Bullet etc. classes. For example:

```
  public class Player{
    ...
    public void OnCollision(Object collider){
       if (collider is Player){...}
       if (collider is Bullet){...}
       ...
    }
    ...
  }

```

This way I can customize the collision effects only when necessary. For example, in my game bullets simply disappear (with an explosion effect) when they collide with anything, so I don't have any 'if' blocks in the Bullet.OnCollision method.
> 1 votes

# Answer
It seems to me that you must not think of it as "player check with enemybullet" but of the collision objects themselves.

Seeing as you already know what types of collision objects you want to support:

> All objects will be encompassed by standard bounding geometry (box or sphere)

It's easy to make a table of the collision you might have.

```
Box     <>   Box
Box     <>   Sphere
Sphere  <>   Box
Sphere  <>   Sphere

```

Personally, here's how I do it in my game. Which, granted, doesn't have very advanced collision detection yet.

* Update all objects in the Scene. An update only affects an object's velocity (direction * speed), not its position. Position + velocity then becomes the future position.
* Clear dead collision objects. For each `ModuleCollision`, check if it's dead and remove it from the list if so.
* Collision checking. Check every `ModuleCollision` with every other `ModuleCollision` and act accordingly if a collision has occurred. A collision might affect an object's velocity.
* Finalize position. Run the `UpdatePost` function for each object, which adds the (perhaps altered) velocity to the position.

Here's what my collision checking looks like:

```
// collision checking using the handshake problem

for (size_t i = 0; i < m_ModulesCollision.size(); i++)
{
    ModuleCollision* coll_left = m_ModulesCollision[i];

    for (size_t j = 0; j < m_ModulesCollision.size(); j++)
    {
        ModuleCollision* coll_right = m_ModulesCollision[j];

        if (coll_left->CheckCollision(coll_right))
        {
            GameObject* obj_left = coll_left->GetOwner();
            GameObject* obj_right = coll_right->GetOwner();

            // this also affects coll_right
            coll_left->CollisionResponse(coll_right);

            obj_left->OnCollision(obj_right);
            obj_right->OnCollision(obj_left);
        }
    }
}

```

I only care about the `ModuleCollision`'s, not the objects themselves. This way you can easily make a list of active objects and only do collision checking on those objects.

What I would suggest if speed is really becoming a problem:

* Put your environment in a static quadtree. This can be built when loading or defined in the level.
* Put everything else in a dynamic quadtree.
* For each object, check for collision with the environment quadtree, then check for collision with the dynamic quadtree. Respond accordingly.
> 0 votes

---
Tags: xna, 2d, collision-detection, optimization, quadtree
---


title: XNA - positioning after rotation

text:
# Question
Title: XNA - positioning after rotation
I have a turret with a 2 gunbarrels. The turret rotates towards my mouse. So far no problem. When it creates a few bullets and positions them at the end of the gun barrels.

Here is the problem. It only works the moment the gun is point upwards. The moment it rotates the end of the gun barrels have moved ofcourse, thus the bullets don't spawn at the end of the gun battels, but at the place the where the gun barrels are when the turret is pointing upwards.

How can I check where the end of the gun barrels are the moment it rotates?

**EDIT:** With the following code it positions the bullet next to turret, not at the end of the gun barrels.

To see what I mean:

```
    Vector2 _bulletPosition = new Vector2();
    _bulletPosition.X = (float)((Math.Cos(_rotation)) * _barrelLenght) + _position.X;
    _bulletPosition.Y = (float)((Math.Sin(_rotation)) * _barrelLenght) + _position.Y;

```

\_rotation = the angle the turret is rotated at.

\_barrelLenght = the length of the barrels.

\_position = the position of the turret.

**EDIT 2:** With this code I get the bullets right between the 2 gun barrels.

```
    _bulletPosition.X = (float)((Math.Cos(_rotation - (float)(Math.PI / 2))) * _barrelLenght) + _position.X;
    _bulletPosition.Y = (float)((Math.Sin(_rotation - (float)(Math.PI / 2))) * _barrelLenght) + _position.Y;

```

With this code I get the 2 bullets at the right end of the gun barrels, but only when the turret is pointing upwards.

```
    _bulletPosition.X = (float)((Math.Cos(_rotation - (float)(Math.PI / 2))) * _barrelLenght) + _position.X + bulletSpawn.X;
    _bulletPosition.Y = (float)((Math.Sin(_rotation - (float)(Math.PI / 2))) * _barrelLenght) + _position.Y + bulletSpawn.Y;

```

I have to get the bulletSpawn relative to the end of the gun barrels position.

**EDIT: THE FIX I FOUND**

I found a fix that worked

```
    //Create Matrix with rotation value
    Matrix rotationMatrix = Matrix.CreateRotationZ(_rotation);
    //Create Vector2 with offset from turret center to end of barrel.
    Vector2 _bulletPosition = point;
    //Do a transform with the bulletPosition Vector2 and the rotationmatrix
    _bulletPosition = _position + Vector2.Transform(_bulletPosition, rotationMatrix);

```

# Answer
> 2 votes
This is pretty elementary math, just use sin and cosine together with the angle the gun is at.

First we need to define a stationary position. This is when the gun points east. The angle is then 0, giving us X = cos(0) = 1 and Y = sin(0) = 0.

Changing the angle of the gun gives us a different position. For example pointing south would give us an angle of 1.5PI which give us the coordinates X = cos(1.5PI) = 0 and Y = sin(1.5PI) = -1.

So these formula give us a direction vector (X,Y) which tells us which direction the turret is facing based on the angle. Now all we need to do is lengthen (multiply) this vector by the length of the barrel and offset it with the position of the turret. This gives us the 'bulletStart' vector.

```
X = cos(angle) * barrelLength + turret.Postion.X;
Y = sin(angle) * barrelLength + turret.Position.Y;

```

Note that the direction vector can directly be used to specify the direction your bullets should fly/face

Edit: re-read and I see you're using double barrels. You can use 1 sprite which shows 2 bullets or you can take the cross product (Vector2.Cross(...)) of the above direction vector to get a vector that points towards the relative 'left' of the direction vector then use the (bulletStart + rleft * barrelDistance) and (bulletStart - rleft * barrelDistance) vectors instead of just the bulletStart vector to place sprites neatly in front of both barrels

# Answer
> 0 votes
I agree with Roy's answer, but I want to provide a different point of view.

What you want to do is transform the spawn point for your bullets depending on the orientation of the barrel.

In 3D math this is typically done with a matrix, but in 2D it's much more common to see people just using plain sine and cosine. I think this is a bit silly, because the problem becomes much easier to solve by using matrix math.

First, let's define the orientation of your turret. It has a position and a rotation.

I'm going to use pseudocode to explain the solution, but it should be easy to convert to XNA C#.

```
// a 3x3 matrix holds a 2D rotation and a 2D translation

mat3x3 transform;
transform.AddRotation(turret.GetRotation());
transform.AddTranslation(turret.GetPosition());

```

This is what the matrix will look like inside:

```
[  cos(deg2rad(angle)),  sin(deg2rad(angle)), 0.0 ]
[ -sin(deg2rad(angle)),  cos(deg2rad(angle)), 0.0 ]
[ position.x,            position.y,          1.0 ]

```

Keep in mind that is an OpenGL matrix, which is *row-oriented*, while DirectX most likely uses a *column-oriented* version.

So how do we get the updated spawn positions? We first define the two spawn points in the object's *local space*. In this case, that means "relative to the camera's position".

```
vec2 spawn_bullet1(-16.0, -16.0);
vec2 spawn_bullet2( 16.0, -16.0);

```

Now we can use our matrix to transform these positions to *world space*:

```
vec2 world_spawn_bullet1 = transform * spawn_bullet1;
vec2 world_spawn_bullet2 = transform * spawn_bullet2;

```

Now you can use these new positions to spawn your bullets and they will always be at the end of the barrels.

That was easy, right? Let's see what happens inside the transformation function:

```
vec2 result;

float x = (a_Position.x * cos(deg2rad(turret_angle))) + (a_Position.y * -sin(deg2rad(turret_angle))) + turret_position.x;
float y = (a_Position.x * sin(deg2rad(turret_angle))) + (a_Position.y *  cos(deg2rad(turret_angle))) + turret_position.y;
float z = (a_Position.x * 0.0)                        + (a_Position.y * 0.0)                         + 1.0;

result.x = x / z;
result.y = y / z;

```

Let's remove the cruft and unnecessary operations:

```
result.x = (a_Position.x * cos(deg2rad(angle))) + position.x;
result.y = (a_Position.y * sin(deg2rad(angle))) + position.y;

```

And you get the same operations as you would when doing it manually, but in convenient matrix form.

What are the benefits of using matrices?

* Matrices can store rotation, translation and scale. You only need to know the relative offset to the turret's position. The rest can be done with the matrix.
* Matrices can be stacked. If you want to put your turret on a bigger ship that moves and rotates, it's a simple of case of multiplying the turret's matrix with the ship's matrix.
* Matrices simplify the math. Instead of keeping track of radians or angles, it's all done and verified by a matrix.

I use a matrix whenever possible, even in a 2D game.

---
Tags: xna, rotation
---


# Question
Title: Shader inputs in a general purpose engine
I'm not familiar with SDKs like Unity or UDK that much, so i can't check this offhand. Do general purpose engines allow users to create custom uniform variables? The way i see it, and the way i have implemented it in an engine i'm writing to learn 3D, is that there is a "set" of uniforms provided by the engine and if you want to write a custom shader then you utilize uniforms you need to create a wanted effect.

Now, the thing is, first of all i'm not an artist, second of all, i didn't have a chance to create complex scenes yet. So my question is, is it common practice to define variables that the engine provides and only allow the user to work with what they're given?

Allowing users to add custom programs and use them where they want is not hard, but i have issues imagining how you'd go about doing the same for uniforms.

# Answer
Yes, they do allow custom uniforms, but they will also fill out a few standard ones. For example, I'm using Horde3D for a project, and one of the shaders contains the following:

```
[[VS_GENERAL]]

#include "shaders/shaderSettings.shader"

#include "shaders/utilityLib/vertCommon.glsl"

#ifdef _F01_Skinning
    #include "shaders/utilityLib/vertSkinning.glsl"
#endif

uniform mat4        viewProjMat;
uniform vec3        viewerPos;
attribute vec3      vertPos;
attribute vec2      texCoords0;
attribute vec3      normal;

#ifdef _F02_NormalMapping
    attribute vec4  tangent;
#endif

varying vec4        pos, vsPos;
varying vec2        texCoords;

#ifdef _F02_NormalMapping
    varying mat3    tsbMat;
#else
    varying vec3    tsbNormal;
#endif

varying vec4        projCoords;

// texture matrix
uniform vec4        textureMatrixRow0;
uniform vec4        textureMatrixRow1;
uniform vec4        textureMatrixRow2;
uniform vec4        textureMatrixRow3;

```

And the material:

```
<Material>
    <Shader source="shaders/water.shader" />

    <ShaderFlag name="_F01_Skinning" />
    <ShaderFlag name="_F02_NormalMapping" />
    <ShaderFlag name="_F02_Character" />

    <Sampler name="albedoMap" map="/textures/dolphin/dolphin_diffuse_V02.dds" />
    <Sampler name="causticMap" map="/textures/caustics/001.dds" />
    <Sampler name="normalMap" map="/textures/dolphin/dolphin_normal_V02.dds" />

    <Uniform name="textureMatrixRow0" a="0.0" b="0.0" c="0.0" d="0.0" />
    <Uniform name="textureMatrixRow1" a="0.0" b="0.0" c="0.0" d="0.0" />
    <Uniform name="textureMatrixRow2" a="0.0" b="0.0" c="0.0" d="0.0" />
    <Uniform name="textureMatrixRow3" a="0.0" b="0.0" c="0.0" d="0.0" />
    <Uniform name="fogColor" a="0.0" b="0.0" c="0.0" d="0.0" />
    <Uniform name="texScale" a="1.0" b="0.0" c="0.0" d="0.0" />
</Material>

```

Here, the `viewProjMat` and `viewerPos` uniforms are filled by the engine, while the others are defined by the user. It seems like a pretty good solution to me.

Note that you can check which GLSL uniform variables are actually used in a shader program:

```
// uniforms

GLint max_name_length;
GLint active_count;
GLchar* name;
GLsizei length = 100;
GLenum type;
GLint size;

glGetProgramiv(m_Program, GL_ACTIVE_UNIFORMS, &active_count);
glGetProgramiv(m_Program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max_name_length);

name = new GLchar[max_name_length];
for (GLint u = 0; u < active_count; u++)
{
    glGetActiveUniform(m_Program, u, max_name_length, &length, &size, &type, name);
    GLint handle = glGetUniformLocation(m_Program, name);

    LOG_INFO("Uniform - %s (%i)", name, handle);

    if (!strncmp(name, "gl_", 3))
    {
        LOG_TRACE("Using deprecated GLSL: %s", name);
    }
    else
    {
        // do something with standard uniforms
    }
}
delete [] name;

```

**EDIT:**

As a user, you see the following:

```
// set the fog color uniform
h3dSetResParamF(res, H3DMatRes::UniformElem, 4, H3DMatRes::UnifValueF4, 0, m_FogColor.x);
h3dSetResParamF(res, H3DMatRes::UniformElem, 4, H3DMatRes::UnifValueF4, 1, m_FogColor.y);
h3dSetResParamF(res, H3DMatRes::UniformElem, 4, H3DMatRes::UnifValueF4, 2, m_FogColor.z);

```

Can't say I agree with the C-style interface, but it works.
> 1 votes

---
Tags: graphics-programming
---


title: 3D terrain map with hexagon grids

text:
# Question
Title: 3D terrain map with hexagon grids
I'm working on a hobby project (I'm a web/backend developer by day) and I want to create a 3D tile (terrain) engine. I'm using XNA, but I can use MonoGame, OpenGL, or straight DirectX, so the answer does not have to be XNA specific. I'm more looking for some high level advice on how to approach this problem.

I know about creating height maps and such, there are thousands of references out there on the net for that, this is a bit more specific.

I'm more concerned with the approach to get a 3D hexagon tile grid out of my terrain (since the terrain, and all 3D objects, are basically triangles).

The first approach I thought about is to basically draw the triangles on the screen in the following order (blue numbers) to give me the triangles for terrain (black triangles) and then make hexes out of the triangles (red hex).

This approach seems complicated to me since I'm basically having to draw four different types of triangles.

The next approach I thought of was to use the existing triangles like I did for a square grid and get my hexes from six triangles as follows

This seems like the easier approach to me since there are only two types of triangles (I would have to play with the heights and widths to get a "perfect" hexagon, but the idea is the same.

So I'm looking for:

1) Any suggestions on which approach I should take, and why.

2) How would I translate mouse position to a hexagon grid position (especially when moving the camera around), for example in the second image if the mouse pointer were the green circle, how would I determine to highlight that hexagon and then translating that into grid coordinates (assuming it is 0,0)?

3) Any references, articles, books, etc - to get me going in the right direction.

Note: I've done hex grid and mouse-grid coordinate conversion before in 2D. Looking for some pointers on how to do the same in 3D. The result I would like to achieve is something similar to this video.

# Answer
I also built a hexagonal terrain for my game. Unfortunately I didn't get much further than that. Here's what it looked like:

Pretty nice, if you don't mind me saying. ;)

First things first: how do you generate a hexagon? Well, a hexagon is a form of polygon. Therefor its edges lie on a unit circle. So we can use sine and cosine to generate six points:

```
for (int i = 0; i < 7; i++)
{
    m_CellOffset[i] = tb::Vec3(
        tb::Math::CosDeg(30.f + 60.f * i) * m_Radius,
        0.f,
        tb::Math::SinDeg(30.f + 60.f * i) * m_Radius,
    );
}

```

That will give us a 3D hexagon, where the points lie on the x- and z-plane.

Then I convert this hexagon to six triangles.

This is useful, because it allows me to make landscapes like the one above, where each vertex can be offset.

Now I can build a grid of hexagons to use as terrain.

However, as you can see, this doesn't really work, because hexagons aren't square and overlap with each other. So to fix that, I just offset every other row:

Now if you're wondering about the best way to store that, I wouldn't be able to tell you. I never got that far.
> 3 votes

# Answer
Answering your question 2 is picking in 3d space, I can think of 3 ways:

1. cast a ray from the camera through the mouse point on the projection plane into 3space and into your grid. This is just like firing a bullet. Where does it hit? Your going to need to know how to do this anyway, right.
2. perform the perspective projection on the hexagonal center points. Which point is closest to your mouse point? (this method is non exact, should work well)
3. draw each triangle (or hexagon) with a unique color into the back buffer. The color is an integer (up to 32 bits!, thats a lot of hexagons). You only draw the back buffer once for each viewpoint. Simply read the color under the cursor. Thats your triangle (or hexagon) This method works very well is used in 3d paint programs, 3d modeling programs, etc. Detailed in the Opengl Red book, "object selection using the back buffer". Though the description is outdated relying on much smaller bits per pixel workarounds.

Since you said you already know about hexagons and mapping I won't detail any of that.
> 2 votes

---
Tags: xna, 3d, tilemap, terrain, hexagonal-grid
---


# Question
Title: Calculating 2D (screen) coordinates from 3D positions in XNA 4.0
I have a program that draws some items to the scene by loading their positions from a file. Now I want to place a Ray on the same location where the items are drawn. So my question is how can I calculate the position of the ray (it's 2D components) by using 3D coordinates of each particular item? The items don't move anywhere, so once they are placed they stay until the end of the programs execution. Thanks.

# Answer
> 1 votes
You can get the screen-space co-ordinates using Viewport.Project:

```
Vector3 screenSpace = Viewport.Project(Point, ProjectionMatrix, ViewMatrix, WorldMatrix);

```

There is also Viewport.Unproject if you want to go the other way.

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


# Question
Title: importing animations in Blender, weird rotations/locations
This is for the Blender 2.6 API.

There are two problems:

**1.** When I import a single animation frame from my animation file to Blender, all bones look fine. But when I import multiple (all of the frames), just the first one looks right, seems like newer frames are affected by older ones, so you get slightly off positions/rotations.

This is true when both assigning `PoseBone.matrix` and `PoseBone.matrix_basis`.

```
bone_index = 0

# for each frame:
for frame_index in range(frame_count):
    # for each pose bone: add a key
    for bone_name in bone_names: # "bone_names" - a list of bone names I got earlier
        pose.bones[bone_name].matrix = animation_matrices[frame_index][bone_index] # "animation_matrices" - a nested list of matrices generated from reading a file

        # create the 'keys' for the Action from the poses
        pose.bones[bone_name].keyframe_insert('location', frame = frame_index+1)
        pose.bones[bone_name].keyframe_insert('rotation_euler', frame = frame_index+1)
        pose.bones[bone_name].keyframe_insert('scale', frame = frame_index+1)

        bone_index += 1

    bone_index = 0

```

Again, it seems like previous frames are affecting latter ones, because if I import a single frame from the middle of the animation, it looks fine.

**2.** I can't assign armature-space animation matrices read from a file to a skeleton with hierarchy (parenting).

In Blender 2.4 you could just assign them to `PoseBone.poseMatrix` and bones would deform perfectly whether the bones had a hierarchy or none at all.

In Blender 2.6, there's `PoseBone.matrix_basis` and `PoseBone.matrix`. While `matrix_basis` is relative to parent bone, `matrix` isn't, the API says it's in object space. So it should have worked, but doesn't. So I guess we need to calculate a local space matrix from our armature-space animation matrices from the files. So I tried multiplying it ( `PoseBone.matrix` ) with `PoseBone.parent.matrix.inverted()` in both possible orders with no luck, still weird deformations.

# Answer
The matrix\_basis of a pose bone is the transform required to go from the bind pose to the current pose, in parent relative space. It's NOT the final matrix that you want.

`pose_bone.matrix_basis = bind_matrix.inverted() * animation_matrix`

Both bind\_matrix and animation\_matrix in the above example are in parent relative space.
> 1 votes

---
Tags: matrix, blender, skeletal-animation, transformation
---


# Question
Title: How do I efficiently code both the client and server at the same time?
I'm coding my game using a client-server model. When playing on singleplayer, the game starts a local server, and interacts with it just like a remote server (multiplayer). I have done this to avoid coding separate singleplayer and multiplayer code.

I have just started coding and have encountered a major problem. Currently I'm developing the game in Eclipse, having all the game classes organized into packages. Then, in my server code, I just use all the classes in the client packages.

The problem is, these client classes have variables that are specific to rendering, which obviously wouldn't be performed on a server.

Should I create modified versions of the client classes to use in the server? Or should I just modify the client classes with a boolean, to indicate if its the client/server using it. Are there any other options I have? I just had a thought about maybe using the server class as the core class, then extending it with rendering stuff?

# Answer
> 25 votes
You should prefer to keep your rendering code separate from your *game logic*, as they are separate concerns.

If you separate your rendering code from your client/server code, you get a couple of advantages:

* Creating a dedicated server will be easier, as any code that renders will be in one place.
* You can separate your `update` phase from your `render` phase, and run them at differing timesteps.
* You can ensure your rendering code doesn't mutate game state, by using `const`, reducing bugs.

# Answer
> 5 votes
I think you should cleanly separate client and server code. The server code and client code should not know about each other except for the functionality exposed with interfaces. The server is not supposed to know anything about rendering, just registering clients, tracking positions, time, etc. If you have cleanly separated concerns it is easier to maintain and further develop your game. Hope this helps a bit.

# Answer
> 5 votes
Separation of concerns FTW, as the others have said, but if your end-goal is to have separate client and server applications, you need to take it a step further. You need to determine what is client-specific, what is server-specific, and what is shared. For everything that is shared, separate it into classes of exclusively-shared code; client- or server-specific classes can then subclass or reference the shared classes as appropriate. Move the shared classes into a separate project, building a "shared library" JAR, and include that JAR in both the client and server projects.

This has a few advantages: it makes the separation of concerns crystal-clear to keep everything in separate projects; it assures you that client and server are starting with the same shared code (as long as they're using the same version of the shared JAR); and it makes it impossible to "accidentally" modify shared code without realizing it. If the shared code is in its own project, you'll know when you're editing anything in that project that you need to be aware of how the changes will effect both the client and the server.

---
Tags: java, networking, server, client-server, metaprogramming
---


title: Joystick example problem for android 2D

text:
# Question
Title: Joystick example problem for android 2D
I've searched all over the web for an answer to this, and there are simular topics but nothing works for me, and I have no Idea why. I just want to move my sprite using a joystick, since I'm useless at math when it comes to angles etc I used an example, Ill post the code here:

```
    public float initx = 50; //og 425;
public float inity = 300; //og 267;
public Point _touchingPoint = new Point(50, 300);  //og(425, 267);
public Point _pointerPosition = new Point(100, 170);
private Boolean _dragging = false;
private MotionEvent lastEvent;

    @Override
public boolean onTouchEvent(MotionEvent event) {

    if (event == null && lastEvent == null) {
        return _dragging;
    } else if (event == null && lastEvent != null) {
        event = lastEvent;
    } else {
        lastEvent = event;
    }
    // drag drop
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        _dragging = true;

    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        _dragging = false;
    }

    if (_dragging) {
        // get the pos
        _touchingPoint.x = (int) event.getX();
        _touchingPoint.y = (int) event.getY();

        // bound to a box
        if (_touchingPoint.x < 25) {
            _touchingPoint.x = 25; //og 400
        }
        if (_touchingPoint.x > 75) {
            _touchingPoint.x = 75; //og 450
        }
        if (_touchingPoint.y < 275) {
            _touchingPoint.y = 275; //og 240
        }
        if (_touchingPoint.y > 325) {
            _touchingPoint.y = 325; //og 290
        }

        // get the angle
        double angle = Math.atan2(_touchingPoint.y - inity,
                _touchingPoint.x - initx) / (Math.PI / 180);

        // Move the beetle in proportion to how far
        // the joystick is dragged from its center
        _pointerPosition.y += Math.sin(angle * (Math.PI / 180))
                * (_touchingPoint.x / 70);
        _pointerPosition.x += Math.cos(angle * (Math.PI / 180))
                * (_touchingPoint.x / 70);

        // stop the sprite from goin thru
        if (_pointerPosition.x + happy.getWidth() >= getWidth()) {
            _pointerPosition.x = getWidth() - happy.getWidth();
        }

        if (_pointerPosition.x < 0) {
            _pointerPosition.x = 0;
        }

        if (_pointerPosition.y + happy.getHeight() >= getHeight()) {
            _pointerPosition.y = getHeight() - happy.getHeight();
        }

        if (_pointerPosition.y < 0) {
            _pointerPosition.y = 0;
        }
    }
    public void render(Canvas canvas) {
    canvas.drawColor(Color.BLUE);
    canvas.drawBitmap(joystick.get_joystickBg(), initx-45, inity-45, null);
    canvas.drawBitmap(happy, _pointerPosition.x, _pointerPosition.y, null);
    canvas.drawBitmap(joystick.get_joystick(), _touchingPoint.x - 26,
            _touchingPoint.y - 26, null);
}

    public void update() {
    this.onTouchEvent(null);
}

```

og= original position. as you can see Im trying to move the joystick, but when I do it stops working correctly, I mean it still works like a joystick but the sprite dosnt move accordingly, if I for example push the joystick down, the sprite moves up, and if I push it up it moves left.

can anyone PLEASE help me, I've been stuck here for sooo long and its really frustrating.

# Answer
> 1 votes
You use `_touchingPoint.x` twice in this code but never `_touchingPoint.y`

```
 _pointerPosition.y += Math.sin(angle * (Math.PI / 180))
                    * (_touchingPoint.x / 70);
 _pointerPosition.x += Math.cos(angle * (Math.PI / 180))
                    * (_touchingPoint.x / 70);

```

I think the first instruction must be

```
_pointerPosition.y += Math.sin(angle * (Math.PI / 180))
                        * (_touchingPoint.y / 70);

```

---
Tags: 2d, android, rotation, movement, joystick
---


# Question
Title: How can I improve this collision detection logic?
I’m trying to make an android game and I’m having a bit of trouble getting the collision detection to work. It works sometimes but my conditions aren’t specific enough and my program gets it wrong. How could I improve the following `if` conditions?

```
public boolean checkColisionWithPlayer( Player player )
{
                    // Top Left             // Top Right                // Bottom Right                                         // Bottom Left                      //
    int[][] PP = { { player.x, player.y }, { player.x + player.width, player.y }, {player.x + player.height, player.y + player.width }, { player.x, player.y + player.height } };

    // TOP LEFT - PLAYER //

    if( ( PP[0][0] > x && PP[0][0] < x + width ) && ( PP[0][1] > y && PP[0][1] < y + height ) && ( (x - player.x) < 0 ) )
    {
        player.isColided = true;
        //player.isSpinning = false;

        // Collision On Right
        if( PP[0][0] > ( x + width/2 ) && ( PP[0][1] - y < ( x + width ) - PP[0][0] ) )
        {
            Log.i("Colision", "Top Left - Right Side");

            player.x = ( x + width ) + 1;
            player.Vh = player.phy.getVelsoityWallColision(player.Vh, player.Cr);
        }
        // Collision On Bottom
        else if( PP[0][1] > ( y + height/2 ) )
        {
            Log.i("Colision", "Top Left - Bottom Side");

            player.y = ( y + height ) + 1;
            if( player.Vv > 0 ) player.Vv = 0;
        }

        return true;
    }

    // TOP RIGHT - PLAYER //

    else if( ( PP[1][0] > x && PP[1][0] < x + width ) && ( PP[1][1] > y && PP[1][1] < y + height ) && ( (x - player.x) > 0 ) )
    {
        player.isColided = true;
        //player.isSpinning = false;

        // Collision On Left
        if( PP[1][0] < ( x + width/2 )  && ( PP[1][0] - x < PP[1][1] - y ) )
        {
            Log.i("Colision", "Top Right - Left Side");

            player.x = ( x ) + 1;
            player.Vh = player.phy.getVelsoityWallColision(player.Vh, player.Cr);
        }
        // Collision On Bottom
        else if( PP[1][1] > ( y + height/2 ) )
        {
            Log.i("Colision", "Top Right - Bottom Side");

            player.y = ( y + height ) + 1;
            if( player.Vv > 0 ) player.Vv = 0;
        }

        return true;
    }

    // BOTTOM RIGHT - PLAYER //

    else if( ( PP[2][0] > x && PP[2][0] < x + width ) && ( PP[2][1] > y && PP[2][1] < y + height ) )
    {
        player.isColided = true;
        //player.isSpinning = false;

        // Collision On Left
        if( PP[2][0] < ( x + width/2 ) && ( PP[2][0] - x < PP[2][1] - y ) )
        {
            Log.i("Colision", "Bottom Right - Left Side");

            player.x = ( x ) + 1;
            player.Vh = player.phy.getVelsoityWallColision(player.Vh, player.Cr);
        }
        // Collision On Top
        else if( PP[2][1] < ( y + height/2 ) )
        {
            Log.i("Colision", "Bottom Right - Top Side");

            player.y = y - player.height;
            player.Vv = player.phy.getVelsoityWallColision(player.Vv, player.Cr);
            //player.Vh = -1 * ( player.phy.getVelsoityWallColision(player.Vv, player.Cr) );
            int rs = x - player.x;
            Log.i("RS", String.format("%d", rs));
            if( rs > 0 )
            {
                player.direction = -1;
                player.isSpinning = true;
                player.Vh = -0.5 * ( player.phy.getVelsoityWallColision(player.Vv, player.Cr) );
            }
            if( rs < 0 )
            {
                player.direction = 1;
                player.isSpinning = true;
                player.Vh = 0.5 * ( player.phy.getVelsoityWallColision(player.Vv, player.Cr) );
            }
            player.rotateSpeed = 1 * rs;
        }

        return true;
    }

    // BOTTOM LEFT - PLAYER //

    else if( ( PP[3][0] > x && PP[3][0] < x + width ) && ( PP[3][1] > y && PP[3][1] < y + height ) )//&& ( (x - player.x) > 0 ) )
    {
        player.isColided = true;
        //player.isSpinning = false;

        // Collision On Right
        if( PP[3][0] > ( x + width/2 ) && ( PP[3][1] - y < ( x + width ) - PP[3][0] ) )
        {
            Log.i("Colision", "Bottom Left - Right Side");

            player.x = ( x + width ) + 1;
            player.Vh = player.phy.getVelsoityWallColision(player.Vh, player.Cr);
        }
        // Collision On Top
        else if( PP[3][1] < ( y + height/2 ) )
        {
            Log.i("Colision", "Bottom Left - Top Side");

            player.y = y - player.height;
            player.Vv = player.phy.getVelsoityWallColision(player.Vv, player.Cr);
            //player.Vh = -1 * ( player.phy.getVelsoityWallColision(player.Vv, player.Cr) );
            int rs = x - player.x;
            //Log.i("RS", String.format("%d", rs));
            //player.direction = -1;
            //player.isSpinning = true;
            if( rs > 0 )
            {
                player.direction = -1;
                player.isSpinning = true;
                player.Vh = -1 * ( player.phy.getVelsoityWallColision(player.Vv, player.Cr) );
            }
            if( rs < 0 )
            {
                player.direction = 1;
                player.isSpinning = true;
                player.Vh = 1 * ( player.phy.getVelsoityWallColision(player.Vv, player.Cr) );
            }
            player.rotateSpeed = 1 * rs;
        }

        //try { Thread.sleep(1000, 0); }
        //catch (InterruptedException e) {}
        return true;
    }

    else
    {
        player.isColided = false;
        player.isSpinning = true;
    }

    return false;
}

```

# Answer
> 0 votes
There is a problem with the bottom right:

```
{player.x + player.height, player.y + player.width }

```

must be

```
{player.x + player.width, player.y + player.height }

```

# Answer
> 1 votes
Instead of reinventing the wheel, I recommend you use a library that will handle collision detection (and possibly physics) for you. JBox2D will handle collision detection and physics for you. If you want to learn to create your own physics / collision engine, take a look at its source code.

I'm sorry if this didn't answer your question fully.

---
Tags: java, android, collision-detection
---


# Question
Title: Is it possible to give an animated GIF a transparent background?
I'm making a Fire Emblem-esque game. There are very cute 2D frames I made for each character, and, like a game like Fire Emblem, I want these characters to animate constantly.

To circumvent the graphics programming involved I came up with a novel idea! I would make each character an animated gif, and only in special conditions ever halt their constant movement - in that case just change what image is being displayed.

Simple enough. But I have a dilemma - I want the background of my .gifs to be transparent (so that the "grass" behind each character naturally shows, as per the screenshot - which has them as still images with transparent backgrounds). I know how to make a background transparent in numerous tools (GIMP, Photoshop). But it seems every .gif creator replaces the transparent background with something and I can't edit it back to transparent.

Is it possible to have a .gif with a transparent "background"? Perhaps my knowledge of file formats is limiting me here.

# Answer
> 4 votes
It's certainly possible (as in the, format supports it), the exact process by which the desired result is achieved will differ from tool to tool. For example, here is a video that purports to illustrate how to make transparent animated GIF images with GIMP. Similarly, this blog post also describes the process.

It largely comes down to making sure your image frames have alpha channels in them before you combine and export them into the final format, regardless of which tool you use.

# Answer
> 0 votes
Also, depending on the media you're using to display the .gif, things may change.

For example, in the good old RPG Maker days, if you saved a .gif with a transparent background on Photoshop, it would look white in RPGM, what you needed to do was make the background a specific pink that RPGM understood as transparent.

---
Tags: graphics
---


# Question
Title: Is there a market for a Text-based empire-building game?
I am working on building a text-based in-browser empire building game. The screen will be split into a console and an EXTREMELY rough vector map of your empire (just squares in a bigger square). Commands such as building and expanding would be typed into the console and automatically reflected in the map. Would there be any market for such a game? Would anyone want to play? To clarify, it would be online and everyone's empire would be in the same 'world'.

# Answer
> 1 votes
There is a 'Roguelike' market (http://en.wikipedia.org/wiki/Roguelike) but they tend to be free games. Even with no graphics, it wont matter if its fun people will play.

---
Tags: game-design, game-mechanics, browser-based-games, text-based
---


# Question
Title: Euler angles to Cartesian Coordinates for use with gluLookAt
I have searched all of the internet but just couldn't find the answer. I am using LibGDX and this is part of my code that loops over and over:

```
public void render()
{
    GL11 gl = Gdx.gl11;

    float centerX = (float)Math.cos(yaw) * (float)Math.cos(pitch);
    float centerY = (float)Math.sin(yaw) * (float)Math.cos(pitch);
    float centerZ = (float)Math.sin(pitch);
    System.out.println(centerX+" "+centerY+" "+centerZ+" ~ "+GDXRacing.camera.position.x+" "+GDXRacing.camera.position.y+" "+GDXRacing.camera.position.z);
    Gdx.glu.gluLookAt(gl, GDXRacing.camera.position.x, GDXRacing.camera.position.y, GDXRacing.camera.position.z, centerX, centerY, centerZ, 0, 1, 0);

    if(Gdx.input.isKeyPressed(Keys.A))
    {
        yaw--;
    }
    if(Gdx.input.isKeyPressed(Keys.D))
    {
        yaw++;
    }
}

```

I might just be bad at the math, but I dont get it. Does someone have a good explanation and an idea about how to deal with this? I am trying to make a first person camera. By the way, the camera is translated by +10 on the Z axis. Currently when I run the application, this is what I get:

Watch video in browser | Download video (for those who cant download the video, everything shakes in a clockwise/anticlockwise action, depending on if I increase or decrease the Yaw value)

-Thank you.

\[edit\]

I fixed it and posted an answer below if you want to see how I did it. This would have not been possible without Sam Hocevar's answer, so big props to him :D

# Answer
If you are making a first person camera, **the center of the scene must rotate around the camera**. So the vector you are building from `yaw` and `pitch` must be *added* to the camera position.

For the first code snippet:

* use smaller increments for `yaw` and `pitch`, because `sin()` and `cos()` use radians, not degrees
* in the `gluLookAt` call, replace `centerX` with `GDXRacing.camera.position.x + centerX` and same for Y and Z.
> 2 votes

# Answer
Thanks to Sam Hocevar's excellent answer I was able to write this:

```
public void render()
{
        float centerX = (float)(MathUtils.sinDeg(yaw)) * Gdx.graphics.getDeltaTime();
        float centerY = (float)(MathUtils.sinDeg(pitch) / MathUtils.cosDeg(pitch) * Gdx.graphics.getDeltaTime());
        float centerZ = (float)(-MathUtils.cosDeg(yaw)) * Gdx.graphics.getDeltaTime();

        Gdx.gl11.glLoadIdentity();
        Gdx.glu.gluLookAt(Gdx.gl11, GDXRacing.camera.position.x, GDXRacing.camera.position.y, GDXRacing.camera.position.z, GDXRacing.camera.position.x+centerX, GDXRacing.camera.position.y+centerY, GDXRacing.camera.position.z+centerZ, 0, 1, 0);

        if(Gdx.input.isKeyPressed(Keys.A))
        {
            yaw-=2;
        }
        if(Gdx.input.isKeyPressed(Keys.D))
        {
            yaw+=2;
        }
        if(Gdx.input.isKeyPressed(Keys.W))
        {
            pitch+=2;
        }
        if(Gdx.input.isKeyPressed(Keys.S))
        {
            pitch-=2;
        }
        if(Gdx.input.isKeyPressed(Keys.R))
        {
            yaw = 0;
            pitch = 0;
        }

        if(pitch>89)
        {
            pitch = 89;
        }else if(pitch<-89){
            pitch = -89;
        }
}

```

There are probably many things that could be improved with this code, but it worked for me so I will leave it. If you stumble upon this in the future, there you go :)
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: Can't find error about playing audio in XNA
I use this in the beginning of the class:

```
SoundEffect bangSound;

```

And then in the constructor I use this code:

```
bangSound = Content.Load<SoundEffect>("Sounds/bang");

```

But I get a red line under the Content, and I can't understand what is wrong? Help is preciated! Thanks!

EDIT: I solved it like this:

```
public Asteroid(ContentManager content, string textureName, Vector2 position)
{
...
LoadContentAudio(content);
....
}

```

With content I can then load the sound like this:

```
    public void LoadContentAudio(ContentManager content)
    {
        bangSound = content.Load<SoundEffect>("Sounds/bang");
    }

```

# Answer
> 1 votes
I think you should load your content in the LoadContent() method. If you don't have this method in your derived game class, create a method that looks like this:

```
public override void LoadContent()
{
    bangSound = Content.Load<SoundEffect>("Sounds/bang");
}

```

# Answer
> 0 votes
Note that your class will need to derive from one of the XNA classes (GameObject or somesuch). Otherwise as John said above, you'll get errors.

If you simply created a class and added the XNA using statements, that isn't enough, it won't know about the static Content object.

---
Tags: xna
---


# Question
Title: Efficient visualization of a large voxelized volume
Lets consider a large voxelized volume stored in an oct-tree or any other convenient structure. This volume represents, for instance, a landscape, where each block is either empty (air), or it has an specific material that will be later used to apply a texture. Voxels that are next to each other represent connected sections of the surface.

What I need is an algorithm to generate a mesh from this voxels that represents the volume, with the following caracteristics:

* All the "holes" in the voxelized volume are correct.
* All the connections are correct, i.e. seamless.
* The surface appears smooth.

In a broad sense, I want to somehow preserve the surface topology, meaning that connected sections remain connected in the resulting mesh and that the surface has a curvature that responds to the voxels topology. Imagine trying to render the Minecraft world but getting the mountain ladders to be smooth instead of blocky.

# Answer
> 2 votes
To generate your basic external, orthogonally-planed mesh: Do a slice-by-slice evaluation of the volumes involved, constructing a submesh from each. Each slice is exactly one voxel in thickness. By basic I mean to suggest starting without smoothing, in order to get a clear understand of the problem. The sliced approach is common in medical imaging, one of the industry birthplaces of volume rendering technology. Where seams are created between individual slices, you can then do post processing to remove those redundant edges (and thus vertices). Let me know if this needs clarification and I'll draw you a simple picture.

For smoothing with effective surface topology preservation, look into marching cubes (note that the algorithm was patented for many years, but that expired in 2005).

Aaron Bishop's latest game Lords of Uberdark does just what you are describing, AFAICT.

---
Tags: algorithm, terrain, voxels, visualization
---


# Question
Title: How to achieve smooth gameplay in a physics based multiplayer game? (2d)
I'm using cocos2d 2.0 and Gamekit for networking. I've got a server/client model. It works over wifi (local) and bluetooth. (Xcode 4.3, Objective C)

Basically, there's a ball and 2 or more players. What I wanted to do is:

The physics is completely simulated on the server. The clients send their inputs to the server and the server sends the position (only the position and rotation that's it) to the clients. The clients than set the position of the objects to the given position datas. The ball is also simulated on the server.

Problem: There can be a high latency and the gameplay would be not smooth on the client side. The players can freely move around and interact with the ball (just pusing it and such things).

I read about prediction but how should it be possible to guess the movement of the player? The player can move completely free (360°). I also read about Servertime and clienttime but I didn't get it very well :/

How could I reduce lag? Please explain your solution because I don't want to just copy and paste it, I want to understand it.

PS: Probably I will have very low ping (1-5 ms) on wifi (local, both devices on the same network), I guess but I want to implement Gamecenter too and than I would need to handle the lag. But handling the lag on wifi/bluetooth would be great to, to achieve smoother gameplay.

# Answer
> 7 votes
Lag results from the speed of light limitation, and the processing speed of network protocol translation and switching in intermediate networking devices and at end points. From yours and your players' point of view, these are invariant factors.

Game that deal *effectively* with lag do so by adjusting player perception of the *impacts* of lag. One example is in how Diablo II originally dealt with player damage in networked games, versus how it did later (and how consequently how WoW does it): never apply full damage all at once, because the player's in-game mistake that caused them to take damage may well have been caused by lag. In proportion to the round-trip packet time, then, be forgiving toward the player, such as (in D2) by dropping health at a certain (possibly increasing) rate, such that they know they have taken damage, they have a good chance of knowing how massive it's going to be, and they have fractionally more time to deal with it by drinking a potion.

You asked about prediction (extrapolation). Players' view of lag can be improved by running your rendering one frame behind, for reasons discussed here (see comments as well, search on "behind"). The idea is that you can extrapolate the next frame's state by looking at motion over the last two frames. Extrapolation works by looking at the deltas (eg. velocities, linear and possibly also rotational) over the last two frames, averaging them, and adding them to the current state. Doing this in 1 dimension (eg. along a straight train track), might be as follows:

* Train velocity in 2nd last frame is 15 units per second
* Train velocity in last frame is 12 units per second
* The delta between these two frames is 12 - 15 = -3 (last minus 2nd last)
* The new velocity in the frame you are about to calculate is 12 + (-3) = 9.

This is a very simplistic example, and there are certainly more physically accuracter ways of doing this (correct use of the equations of motion). However doing this in 2 or 3 dimensions is much the same, only you'll be using some trig (Pythagoras) to calculate actual vector magnitudes so as to do the extrapolation step.

Gaffer's Networked Physics article is a great place to get up to speed on the various concerns and potential solutions.

Possibly most importantly, you will not want to do your testing on your home network, cf. the experience of the X-Wing vs Tie Fighter team! Instead, get a realistic, even slow remote system that you can work with to do your testing, or alternatively use a lag-simulation app to give you a high latency, possibly packet-lossy environment in which to do your testing. This will be hard to start with but will reduce time spent on implementation in the long run.

# Answer
> 4 votes
Prediction is the way to go. It still works with 360° movement. All Quake games use it for example.

The thing with prediction is that it fails as soon as the direction of movement of a predicted object changes (significantly). If this happens very frequently, prediction can't help you much.

There is no other "magic" to fix latency, other than trying to reduce latency as much as possible. One being not to allow play over high-latency connections (3G).

You also have some influence by the amount of data you're sending, and how many packets you're sending. If you're choking the line with too much data, lag is increased. Or maybe what you perceive as lag is merely packets being dropped, never to arrive.

Most multiplayer games compress the data they send, or are very clever about when and how often they send certain information.

For example if you send position information, that's usually a CGPoint. A CGPoint consists of two float values (x,y). Each is 4 Bytes, which makes each CGPoint 8 bytes. You can safely reduce that to two Int16 to a total of 4 Bytes. Convert to Int16 by multiplying the point coordinates by 10, and on the receiving end divide by 10. For example: x,y = 1.2094, 204.7897 multiplied by 10 and represented as Integer gives you: 12, 2048. On the receiving end you'll divide by 10.0f and you get x,y = 1.2, 204,8.

In many cases it is ok to lose floating point precision in favor of saving bandwidth. Your object positions are also limited to a range of -3200 to 3200 (or 0 to 6500 if you use UInt16). But I doubt doing this optimization will have an effect on your game as it doesn't sound full of game objects.

Another issue is sending at 60 fps, which may easily be overkill. Imagine you accumulate 100 Bytes to be sent over the network every frame. At 60 fps that makes 6 Kilobytes per second. That's significant for mobile phone upstream rates. If you only send the same data every 6 frames you can cut the datastream down to 1 Kilobyte per second.

---
Tags: networking, cocos2d, physics, multiplayer, latency
---


# Question
Title: Smooth animation on a persistently refreshing canvas
Yo everyone!

I have been working on an Isometric Tile Game Engine in HTML5/Canvas for a little while now and I have a complete working game. Earlier today I looked back over my code and thought: "hmm, let's try to get this animated smoothly..."

And since then, that is all I have tried to do.

***The problem***
I would like the character to actually "slide" from tile to tile - but the canvas redrawing doesn't allow this - does anyone have any ideas....? Code and fiddle below...

**Fiddle with it!** http://jsfiddle.net/neuroflux/n7VAu/

```
<html>
<head>
<title>tileEngine - Isometric</title>
<style type="text/css">
* { margin: 0px; padding: 0px; font-family: arial, helvetica, sans-serif; font-size: 12px; cursor: default; }
</style>
<script type="text/javascript">
var map = Array( //land
    [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],
    [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],
    [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],
    [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],
    [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],
    [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],
    [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],
    [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],
    [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]],
    [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
);
var tileDict = Array("http://www.wikiword.co.uk/release-candidate/canvas/tileEngine/land.png");
var charDict = Array("http://www.wikiword.co.uk/release-candidate/canvas/tileEngine/mario.png");
var objectDict = Array("http://www.wikiword.co.uk/release-candidate/canvas/tileEngine/rock.png"); //last is one more
var objectImg = new Array();

var charImg = new Array();
var tileImg = new Array();

var loaded = 0;
var loadTimer;
var ymouse;
var xmouse;
var eventUpdate = 0;

var playerX = 0;
var playerY = 0;

function loadImg(){ //preload images and calculate the total loading time
    for(var i=0;i<tileDict.length;i++){
        tileImg[i] = new Image();
        tileImg[i].src = tileDict[i];
        tileImg[i].onload = function(){
            loaded++;
        }
    }
    i = 0;
    for(var i=0;i<charDict.length;i++){
        charImg[i] = new Image();
        charImg[i].src = charDict[i];
        charImg[i].onload = function(){
            loaded++;
        }
    }
    i = 0;
    for(var i=0;i<objectDict.length;i++){
        objectImg[i] = new Image();
        objectImg[i].src = objectDict[i];
        objectImg[i].onload = function(){
            loaded++;
        }
    }
}

function checkKeycode(event) { //key pressed
    var keycode;
    if(event == null) {
        keyCode = window.event.keyCode;
    } else {
        keyCode = event.keyCode;
    }
    switch(keyCode) {
        case 38: //left
            if(!map[playerX-1][playerY][1] > 0){
                playerX--;
            }
            break;
        case 40: //right
            if(!map[playerX+1][playerY][1]  > 0){
                playerX++;
            }
            break;
        case 39: //up
            if(!map[playerX][playerY-1][1]  > 0){
                playerY--;
            }
            break;
        case 37: //down
            if(!map[playerX][playerY+1][1]  > 0){
                playerY++;
            }
            break;
        default:
            break;
    }
}

function loadAll(){ //load the game
    if(loaded == tileDict.length + charDict.length + objectDict.length){
        clearInterval(loadTimer);
        loadTimer = setInterval(gameUpdate,100);
    }
}

function drawMap(){ //draw the map (in intervals)
    var tileH = 25;
    var tileW = 50;
    mapX = 80;
    mapY = 10;
    for(i=0;i<map.length;i++){
        for(j=0;j<map[i].length;j++){
            var drawTile= map[i][j][0];
            var xpos = (i-j)*tileH + mapX*4.5;
            var ypos = (i+j)*tileH/2+ mapY*3.0;
            ctx.drawImage(tileImg[drawTile],xpos,ypos);

            if(i == playerX && j == playerY){
                you = ctx.drawImage(charImg[0],xpos,ypos-(charImg[0].height/2));
            }
        }
    }
}

function init(){ //initialise the main functions and even handlers
    ctx = document.getElementById('main').getContext('2d');
    loadImg();
    loadTimer = setInterval(loadAll,10);
    document.onkeydown = checkKeycode;
}

function gameUpdate() { //update the game, clear canvas etc
    ctx.clearRect(0,0,904,460);
    ctx.fillStyle = "rgba(255, 255, 255, 1.0)"; //assign color
    drawMap();
}
</script>
</head>
<body align="center" style="text-align: center;" onload="init()">
    <canvas id="main" width="904" height="465">
        <h1 style="color: white; font-size: 24px;">I'll be damned, there be no HTML5 & canvas support on this 'ere electronic machine!<sub>This game, jus' plain ol' won't work!</sub></h1>
    </canvas>
</body>
</html>

```

# Answer
You can animate your character by interpolating from the initial position to the target position.

You would have to update the position of the player inside your `gameUpdate` method, *before* calling `drawMap();`. To avoid strange movements, you'll have to lock/ignore player input for that period of time. This can be done easily by setting a flag `isAnimating` to `true` and simply ignoring key-input when `isAnimating == true`.

If your game gets more fleshed out, your game code will increase. If that's the case it's probably a good idea to separate your code into classes (I know, not so easy with JavaScript) and also implement a proper game-loop: Tips for writing the main game loop?
> 8 votes

# Answer
I think it would be best if your tiles are on a separate canvas. This would make what you want really easy - you just clear the top canvas on each frame, while the background remains. As bummzack said, you might have to lock controls during the animation.

Otherwise you could clear only the origin and destination tiles and redraw them on each frame, but this seems like more (unnecessary) work.

Btw using the arrow keys on a 45 degree isometric map makes controls very difficult for me. Better use some of the letter keys, as they are laid out in a 'hex' pattern, making diagonal movements more intuitive.
> 3 votes

---
Tags: javascript, html5, html-canvas
---


# Question
Title: Creating a WARP device in managed DirectX
I have a very old graphic card that only supports shader model 2, but I need shader model 3 or up for the app I am developing. I tried to use a reference device but it seems to run very slowly, then I found some samples in C++ that allows me to change to a WARP device and the performance is good. I am using C# and I don't know how to create such type of device. So the question is: how do I create a WARP device in C#? Thanks in advance.

# Answer
> 0 votes
Managed DirectX is a D3D9 based API. WARP is a D3D10+ only technology. You might want to look at other managed DirectX wrappers that support D3D10+, these should be able to use WARP.

# Answer
> 0 votes
Your only option if you want to stick with MDX use to use Windows 8.

In Windows 8 D3D9 falls back to WARP when there's no hardware device, so you can disable your graphics card in device manager to switch to WARP.

---
Tags: directx, graphics
---


title: Shadows moving with camera.

text:
# Question
Title: Shadows moving with camera.
I'm using MJP's Cascade Shadow Map code and I'm having major issues with the shadows moving with the camera. Here a video to demonstrate what's going on. Also, is there a way to fix the dueling frustum issue? It's annoying seeing them pop in and out of corners of the screen.

Video of the shadows

c# and shader code

# Answer
> 3 votes
It looks to me like your shadow render is lagging one frame behind the geometry render (or vice versa). I've had this in my own projects before now. Check your update and render order: you may be doing something like:

```
a) Update world/camera state
b) Draw Geometry
c) Draw shadows
d) Calc shadows with current (i.e. OLD) geom state

```

# Answer
> 0 votes
I'm not familiar with cascade shadow mapping (yet) but that sort of thing seems to happen in simple shadow mapping too, when using wrong parameters in the calculation of the shadow projections.

This should help (with near/far planes too): http://msdn.microsoft.com/en-us/library/windows/desktop/ee416324(v=vs.85).aspx

In your video the shadow edge seems to move bit more than just a 'shimmering' but it could be the result of a really far light source.

---
Tags: xna, shadows
---


# Question
Title: Fixed-Function vs Shaders: Which for beginner?
I'm currently going to college for computer science. Although I do plan on utilizing an existing engine at some point to create a small game, my aim right now is towards learning the fundamentals: namely, 3D programming. I've already done some research regarding the choice between DirectX and OpenGL, and the general sentiment that came out of that was that whether you choose OpenGL or DirectX as your training-wheels platform, a lot of the knowledge is transferrable to the other platform. Therefore, since OpenGL is supported by more systems (probably a silly reason to choose what to learn), I decided that I'm going to learn OpenGL first.

After I made this decision to learn OpenGL, I did some more research and found out about a dichotomy that I was somehow unaware of all this time: fixed-function OpenGL vs. modern programmable shader-based OpenGL. At first, I thought it was an obvious choice that I should choose to learn shader-based OpenGL since that's what's most commonly used in the industry today. However, I then stumbled upon the very popular **Learning Modern 3D Graphics Programming** by Jason L. McKesson, located here: http://www.arcsynthesis.org/gltut/

I read through the introductory bits, and in the "About This Book" section, the author states:

> "First, much of what is learned with this approach must be inevitably abandoned when the user encounters a graphics problem that must be solved with programmability. Programmability wipes out almost all of the fixed function pipeline, so the knowledge does not easily transfer."

yet at the same time also makes the case that fixed-functionality provides an easier, more immediate learning curve for beginners by stating:

> "It is generally considered easiest to teach neophyte graphics programmers using the fixed function pipeline."

Naturally, you can see why I might be conflicted about which paradigm to learn: Do I spend a lot of time learning (and then later unlearning) the ways of fixed-functionality, or do I choose to start out with shaders? My primary concern is that modern programmable shaders somehow require the programmer to already understand the fixed-function pipeline, but I doubt that's the case.

**TL;DR** = As an aspiring game graphics programmer, is it in my best interest to learn 3D programming through fixed-functionality or modern shader-based programming?

# Answer
> 30 votes
I don't buy the argument that it's easier to start with the fixed-function stuff. It might be the case that the fixed-function lets you do certain things with less code - in fixed-function OpenGL, for instance, you can get some very basic lighting/shading going by doing `glEnable(GL_LIGHTING)` and a few other calls. The trouble is that as soon as you want something slightly different - per-pixel lighting, say, instead of per-vertex lighting - you have to abandon the fixed-function stuff entirely and write a shader to implement both whatever fixed functionality you were using before, plus whatever you wanted to change.

It just seems like it would be simpler and less confusing to be using shaders the whole time. Shaders do need a bit more setup work as you have a separate source file that needs to be loaded and compiled, some extra C calls to look up and set parameters, etc. But once you've got a shader going, it's the easiest thing to code a few different effects, try out different ideas, etc. And you don't need to care about where the limits of the fixed-function system are and whether it can or can't do what you want; shaders can do whatever you can write code for, modulo the usual limits of performance and memory.

# Answer
> 3 votes
I would say to start with fixed function on GLUT. I'm not going to say much about this, but the ideas behind shaders are pretty complicated and the requisite knowledge is basic 3d programming (ie vertex creation and transformation matrices etc). There are a lot more places you can screw up using shaders, there's that much more to code.

Check out my tutorial, and these lighthouse3d ones

# Answer
> 2 votes
I second going straight for shaders. It's not really *that* much harder to set up, and when you pass that first hurdle you have full power at your fingertips.

More to the point, you'll find that shader programming more closely matches the mathematical equations you see in books and graphics lectures at college.

# Answer
> 0 votes
I would suggest using the fixed function pipeline as a backbone of your program. I find it to be easier to have something show up using it instead of purely shaders. Then, when you know you haven't messed up your vertices or normals, you can slowly but surely inch your way into the shading world.

---
Tags: opengl, 3d, shaders, graphics-programming
---