title: Main characteristics of a game

text:
# Question
Title: Main characteristics of a game
I was doing some reading for college and I searched for

* "Main characteristics of games"
* "Main characteristics of video games"

and other similar ones, the result were a bunch of psychological studies and some non totally related links. The bottom line there was no real definition. I can see why, however I m suprised there are no attempts

I m going to think I m looking for the wrong thing, so can you help?

My purpose is to try to understand what is a video game and what isnt. ie: bad games are still games, so fun and immersion are not characteristics of a game ( before I started thinking about this I thought that was the case)

Cheers

# Answer
> 8 votes
> My purpose is to try to understand what is a video game and what isnt.

There isn't one universally accepted definition of what constitutes "videogame" and what doesn't. Here's my take on it.

First, let's separate the definition of "game" from "videogame". Yes, really.

A "game" is an activity with one or more objectively-determined victory conditions, whereby one or more players attempt to achieve these conditions with their actions governed by a series of objective rules. This covers table-top games, most sports (though the objectivity of referee rulings can be in question), and most things we call videogames.

This definition arises from comments made by Will Wright, about the differences between a "toy" and a "game". Games have goals; toys don't. You can do various stuff with a toy, and you may find that stuff fun. But the toy doesn't say whether you win or lose; that's up to you to decide. It makes no value judgements about how well you used the toy.

Games do have goals. Games do have built-in victory conditions. Games put values on certain actions above others; those that come closer to achieving the victory conditions are better than those that don't.

A "videogame" is a computer program of some form designed *specifically* for the entertainment of the user(s).

That last part is the key for me. You can have fun with Photoshop and you can have fun with Mario Paint. But these are two very different applications. The former has a clearly defined purpose: to create and edit images. If you find using Photoshop fun, it is only because you like creating and editing images.

Mario Paint is designed to be an enjoyable, fun experience. You poke at it, and exciting things happen. That's why it has a music editor. That's why it doesn't have a lot of the features Photoshop does. So while you can certainly do more with Photoshop, the experience of using Mario Paint is more geared towards user pleasure. You're not creating anything you possibly could or something specific; you're creating fun pictures of stuff. Not particular stuff, but stuff in general. It's a restricted environment, and the restrictions speak to a certain kind of image.

The same goes for web browsers. A web browser itself is not a videogame, even if all you use it for is personal enjoyment. That is not its designed purpose; it's purpose is to feed you information. If you find that information enjoyable, so be it. But it could just as easily feed you Goatse.

You may notice that the definition of "game" and "videogame" have little in common. Mario Paint is very much a videogame, but the lack of *explicit* goals (built into the rule system of the program) mean that it is *not a game*.

It's important to make that distinction. Just as you can have games that aren't videogames, you can have videogames that aren't games. The term "videogame" only originated because the early videogames all *were* games. Space War, Pong, Pac-Man, Defender, all of these had rule-bound action and objective victory conditions (score the most points, hit the other guy, etc).

# Answer
> 4 votes
If you're essentially looking for what the definition of a 'game' is, then there are many different definitions.

You will find some of those definitions on this page, under the heading *"So, what is a game, anyway?"*

---
Tags: game-design
---


# Question
Title: How can people recognize what engine a game uses, based off its graphics?
With many games, you can say "oh, that's the *Unreal Engine*, for sure", or "this was made with an upgraded *Rockstar Advanced Engine*". We can often recognize the engine used for a game just by looking at its graphics, disregarding user interface.

Why is this? All game engines use the same 3D rendering technology that we all use, and the different games usually have a distinct art style. What's left to recognize?

# Answer
Primarily I'd imagine this is down to the shaders. For example, the Unreal engine will have a certain method of handling HDR, a certain method of handling bump mapping, a certain method of handling light scatter, etc.

They will also have a uniform level of clarity in terms of constraints such as texture sizes and colour support.

Additionally the algorithms will be similar. Objects will be tessellated using the same algorithms. AI will make decisions according to the same decision-making architectures.

If the bump mapping is causing insane specular and reacts strongly to changes in lighting for example, you immediately start thinking Doom 3 engine. That's because that shader code is shared between every game using the engine. You wouldn't want to rip something like that out.

"All game engines use the same 3D rendering technology that we all use"

The technology is the same, but the rules that govern how the world actually looks (eg. lighting, tessellation, LOD , etc) are all written by the developer. The 3D rendering technology doesn't have that much to do with the visual quality of the things on screen. Even the rules for applying flat ambient lighting is left up to the developer (assuming you're not using Fixed-Function Pipelines).

You can make your OpenGL app look just like your DirectX app with often trivial difficulty. The underlying rendering technology really doesn't have that much impact except with regards to speed.
> 50 votes

# Answer
Engines often provide high-level abstractions, which leads to subtle similarities in the games that use them—a “side-channel attack” if you will.

These include:

* Environment rendering abstractions, such as grass or trees.
* Ground material mixing.
* Triggers and events systems have similar error behaviour.
* systems.
* Shadow rendering.
* Postprocess handling.
* Z-Buffers/Depth buffers make same errors at the same distances.
* AI behavior issues, and script handling.
* Smoke, fire, rain, dust, snow, water, clouds, reflection.
* Some nice texture/resource that everybody likes to use. :)
* Sky handling / sky boxes.
* Caching.
* Material presets that the developer didn't bother changing.
* Shader math. (Engines may have their own variant of the same algorithm.)
@wkerslake adds:
* Level size / streaming.
* Physics in general.
> 18 votes

# Answer
It's funny because it's true, the lighting and further post-process effects can easily expose the underlying engine.
> 15 votes

# Answer
Animations also give it away. Every engine handles them in a different way and they also look and feel different while playing.

You can spot engine limitations on animations and tell which engine was used by that too.
> 4 votes

# Answer
I never knew you could really do that.

Easiest ways to tell:

* Very often they have big 'Unity Engine' or 'Unreal Technology' logos on startup.
* Companies reusing game engines - A 'Rockstar Games' open world game is almost certainly going to use a GTA tweaked engine.
> 3 votes

# Answer
There are subtle differences in the engines and what they're good and bad at that is easy to spot from game to game.

The exact combination of these traits can often identify the engine.
> 3 votes

# Answer
Aside from the 3D graphics, we also recognize common shared behaviors in the game engine itself. There are a lot of little variables that go into every part of a game, and certain combinations, once set, remain a part of all games using that engine.

Such variables could include: character move speed, character movement acceleration, camera pan speed, camera pan acceleration, camera pan smoothness, and so on.

This is very apparent with mods or games that started as mods (hello Source engine games) because once the design is past the basics, rarely will anyone go back to tweak something like the acceleration rate of a jump. The effect of all those little variables is that the games "feel similar" but in a way that's hard to pin down.
> 2 votes

# Answer
You can tell Unreal games because they all use the same incredibly bad skin shader, and the same stupid "physics" puzzles.
> 1 votes

# Answer
A lot of what people say is a typical engine is actually more art related. Engines empower or impose restrictions on art assets but the design and execution of how things feel is largely an art issue. Take for example the faces in Oblivion; So many people were blaming the engine for the slightly less than convincing characters. This was clearly an issue with the art, or if not that then the section of Bethesda's code that blended faces together, rather than the whole 'engine'. Similarly, when people see shiny, grimy, steroid abusing space marines they'll think 'Unreal' but this is more of an art direction, rather than a facet of the underlying engine that displays that art. Even though different studios make grimy space marine games they'll often use unreal because it's been proven to be able to make that sort of game.
> 1 votes

# Answer
I think there are more subtle signs than what you see. Quake felt the same on OpenGL, Software, and PowerVR - despite unique looks on each.

For instance, the Quake-Engine games, to me felt more solid, whereas Build engine felt more flimsy, and Unreal felt kind of abstracted.

This is largely physics - and I suspect something to do with the game loop as well.
> 1 votes

# Answer
I've found that facial animations are usually a dead giveaway. There is a lot of variation and even with different art you can still see the same patterns in the textures.
> 0 votes

# Answer
I often recognize engines by their physics. Most notable here is the Source engine, particularly the part which picks up objects. You'll notice that in many games picking stuff up is similar. I believe this is due to the engine. I also agree that different engines handle light differently, so you can recognize them by that.
> 0 votes

---
Tags: 3d, graphics
---


title: Optimum Screen Resolutions

text:
# Question
Title: Optimum Screen Resolutions
Most PC games nowadays obviously come with the standard option to change the game's resolution from between 640x480 to 1920x1080 on average, depending on your monitor and whether or not you are playing in windowed mode. However, when developing a retro pixel art game, allowing the resolution change to be between 640x480 and 1920x1080 is rather absurd.

So in a pixel art game where, at default resolution, one frame of the main character's sprite is 16x32 pixels, what would you like to see the game's default resolution to be, and by how much would it scale with each resolution option? Would a square screen be better than a widescreen? How many map tiles (at 32x32) would be best to display across and down?

So, in general, what would be the optimum game screen size and at what resolution for a pixel art game now? Your opinions are appreciated.

# Answer
Depends on the game, if the game is single-player, let the user select a resolution, if they are happy for small characters, they can have it, if they want to feel connected with the game, they can use a lower resolution.

Games like Civilization opt for this method.

However, if you're building a multiplayer game, you're going to need a fixed resolution, providing players with different view-ports is somewhat unfair - if I can see more of the map because I run at 1920x1200 and you're stuck at 640x480.

Games like Command and Conquer (at least the old ones) opt for this method.

You could render your sprites at a high resolution, and then scale them at render time, someone at your pristine resolution would see the characters at 1:1 someone at the lower resolutions would see a scaled image.

I believe Diablo II did this, as it allowed 640x480 or 800x600

What is the perfect resolution? well, personally I think 1920x1200 because that's what my monitor is :) However a more objective answer may come from some statistics, perhaps the Steam Hardware Survey would be a good place to start.
> 6 votes

# Answer
In order to still get something that looks decent by modern standards you should choose something around 512x320 (16:10). I'm not a big fan of the retro pixel look, I guess it makes the art job smaller, but you could go with a simplistic cartoony look to make the same saving and still let players keep all their pixels.
> 1 votes

# Answer
IMHO you should allow your game to run at a native monitor resolution which typically will be some kind of widescreen aspect ratio, 1600x900, 1920x1080 or 1920x1200 etc. For the unusual case of a 4:3 monitor leaving black borders on top and bottom should be fine, unless you want to be extra flexible.

If your art is too small for this, scale your game up but leave the resolution high as changing it may be a pain and is sometimes tricky, especially on multi-monitor setups. By allowing your game to run in a high-res window you'd be dodging the problem altogether.

For retro-style image scalers these links should get you started:
> 1 votes

---
Tags: resolution, screen, pixel
---


# Question
Title: Setting up speedtests in Actionscript 3 for an entire game
I'm very new to this so please forgive the questions possibly ill-stated nature.

Firstly is this even a valid way to speedtest:

```
public function L1() {

        tree.x = 200;
        tree.y = 200;
        tree.healthPoints = 0;
        addChild(tree);
        var myTimer:Timer = new Timer(100,60);
        myTimer.addEventListener(TimerEvent.TIMER,someFunction);
        myTimer.start();
        addEventListener(Event.ENTER_FRAME, speedTest)

    }
    function someFunction(event:TimerEvent) {
        t++
    }
    public function speedTest (e:Event) {
        if (tree != null) {
            do { tree.healthPoints += 1; }
            while (tree.healthPoints < 10000) ;
            tree.healthPoints = 0;
                trace (t);

        }
    }

```

Secondly: I want to actually speed-test the entire game somehow to check if adding new features or rewriting current features actually optimizes the game or not.

What are some ways to do this?

# Answer
That doesn't seem like a very useful way to do it IMO. Any profiling methods should introduce a consistent overhead, but relying on the callbacks may reduce accuracy.

Try using the Date class. Or better yet, a legit profiler like The Miner
> 1 votes

---
Tags: actionscript-3, optimization, actionscript
---


# Question
Title: How do I handle walking up and down bridges at any angle?
I'm currently trying to create a 2D platformer puzzle game like *Mario vs. Donkey Kong: Mini-land Mayhem!* within Flash. My issues reside in the bridge collision with the walking AI.

The game allows the player to create a bridge from one end point to another at any angle. Then the player's AI mummies (in this case) walk across the bridge to reach another platform.

Now, seeing that the bridge can be constructed at any angle, I'm only going to have a rotated rectangle to represent the body of it.I obviously can't use the typical AABB to check collision against this, instead it looks like I'm going to need to do a SAT or pixel perfect check.

The AI mummy must always stick to the platform or bridge as it walks across it (not to mention rotate to the bridge's angle). Therefore, I suppose I'm going to need some gravity and sliding collision? The walking speed should also be the same on both the platform and bridge.

Lastly, since I'm using a grid for my platform tiles (including the end points) connecting a bridge to them isn't going to be perfect. Going up and down the bridge may need some offsetting with floor in order to make a smooth transition from or two the bridge.

An example

Some things I have tried in the past week or two:

1. Using SAT collision with rotated rectangular bodies on the mummy and the bridge. I tried having the mummy walk up the bridge by adding 3 mini-hitboxes on the bottom-left, bottom-mid, and bottom-right to him. I had a hard time trying to get this to look right and trying to stick all of the hitboxes onto the bridge and the floor (especially when I rotated the mummy to that of the bridge).
2. Using Box2D Flash port library. Just doing something simple as this is seeming like an uphill battle with this physics engine. It looks as if it will be troublesome to get a predictable movement with a constant speed especially when going up the bridge. I've tried their 'conveyor' example, but for some reason, the classes that were used for it are missing in the Flash port. I've also tried disabling the physics and just using it for collision detection, however I dislike it entirely. I also don't receive any contact information for collision on the sensors (like distance, normal, point of collision, etc.). I'm better off with using my own SAT implementation for this task.
3. I've also tried placing nodes above each end point and when a bridge is connected, the mummy will know to go from one node to the other when he collides with the starting node itself. This has drawbacks of needing to offset the nodes perfectly so the mummy's feet will always be on the bridge, so I'd have to make sure to never change the size of the character and the bridge. Also, I'd need two nodes per end point, since going down and up a bridge will need different offsets.

It feels as though a fully fledged physics engine just doesn't feel right for this game. It would handle a lot of my current problems, but it will be introducing more at the same time. If I want a smooth walking transition from the platform to the bridge, it seems as it's the only choice.

Now my question is how would you guys go about having the mummies walk up and down a bridge smoothly at a constant speed and angle? Just use a physics engine? Create your own physics? Or trying raycasts?

Thanks

# Answer
You should set up four points on each side of the enemy's/player's feet. Two represent the range in which the feet should make contact with the ground. The other two represent the range walk-able slope.

This is a picture representing an enemy moving right, represented by a box, with each of the points mentioned drawn.

The fist picture is how it should be, with the bottom two points under the ground and the top two points above the ground. There is no need to change altitude.

In the second picture, only the top point isn't colliding with the ground, so it must slope upward. In the code, you would then adjust the enemy's y-location pixel-by-pixel until the second-to-top point no longer collides.

In the third picture, only one point collides, so you must adjust the y-location pixel-by-pixel downward until the second lowest point collides.

You would use these points only when the enemy moves right. If he moves left, check points set up the same way but on the left side of the bounding box.

There are two other cases that can happen. In one, no point collides, which means the enemy is hanging over the edge of a cliff. In the other, every point collides, meaning the enemy is walking straight into a wall. You can use additional code under these special circumstances.
> 1 votes

# Answer
I guess I would implement almost the same method as your 3rd, create some lines representing platforms and bridges. but the offset is no big deal, checking distance between a line and a point is really easy to calculate(just check the wiki page).

* for each frame
* move the object with constant speed in the same direction as the line
* check if it's distance to bridges is less than bridge width
    1. if it's near enough change the line mummy is walking on
    2. if not do not do anything

this is a simple enough algorithm to implement. note that each line is represented by two points. which are head and tail of the line. you can also calculate normal value for that vector, and rotate the character to that angle.
> 1 votes

---
Tags: 2d, collision-detection, physics, flash
---


title: Time Required for Animation to Finish

text:
# Question
Title: Time Required for Animation to Finish
Using a tutorial found on the AppHub, I've been attempted to add controls to a sample sprite sheet. I am able to get all the animations working, but for stuff like punching or stabbing, the animations require a timer to stop them from playing repeatedly. XNA uses a default framerate of 60, but I have the animations running at 10 FPS using the following code:

```
int punchIndex = walk.GetIndex("obj_Walk000");

punchIndex += (int)(time * animationFPS) % punchFC;
batch.Draw(punch.Texture, position, punch.SourceRectangle(punchIndex), Color.White, rotation, origin, 1.0f, SpriteEffects.FlipHorizontally, 1.0f);
break;

```

Where animationFPS = 10 and punchFC is 6, which is the number of frames in the animation. Using this data, I have calculated a required time of 0.5 seconds for the animation to complete, but that seems to be incorrect, so I'm looking for someone to show me how to do the math properly.

# Answer
> 5 votes
First of all I recommend separating it so that the frame is updated in the `Update` method instead of the `Draw` method. That's because XNA is free to skip a few `Draw` calls to make up for lost time when the game runs slowly, but not `Update`, so it should run more consistently.

It's also a better idea to leave the `Draw` method just for rendering, and putting any state changes in the `Update` method of your classes.

Now for your problem, here's the basic structure of how to enforce an animation framerate indepdentent of the game's framerate (in this example 10 FPS):

```
private float _timer = 0.0f;
private float _framerate = 10f;
private int _currentFrame = 0;
private int _frameCount = 6;
private bool _animating = true;

public void Update(GameTime gameTime)
{
    if(!_animating) return;

    _timer += (float)gameTime.ElapsedGameTime.TotalSeconds;

    if (_timer >= 1.0f / _framerate)
    {
        _timer -= 1.0f / _framerate;
        _currentFrame = (_currentFrame + 1) % _frameCount;

        if(_currentFrame == 0)
        {
            _animating = false;
            _timer = 0f;
        }
    }
}

public void Draw(GameTime gameTime)
{
    // Draw _currentFrame
}

```

Of course you can precalculate and store `1.0f / _framerate` to avoid having to recompute it every frame.

---
Tags: xna, animation, spritesheet
---


# Question
Title: Waiting specific time to increase sound libgdx
I want to wait a moment (.5 seconds) before I increase the sound, how can i achieve this without using Thread.sleep, because i want my game to keep runnig.

# Answer
> 3 votes
You can either use a java timer approach: http://developer.android.com/reference/java/util/Timer.html

Or you could simply keep track of the time elapsed since the increase volume action began. Maybe something like this in your render method or somewhere else:

```
float elapsedTime;
long actionBeginTime;
boolean volumeIncreasing=false;
public void render () {
    if(volumeIncreasing){
        elapsedTime=(System.nanoTime()-actionBeginTime)/1000000000.0f;
        if(elapsedTime>0.5f){
            increaseVolume(); //your method that increases volume
            volumeIncreasing=false; //can be set here or in increaseVolume()
        }
    }
}

```

Of course you need to set volumeIncreasing to true and actionBeginTime=System.nanoTime() somewhere when the action begins.

---
Tags: java, sound, libgdx
---


title: Need help with Shadows

text:
# Question
Title: Need help with Shadows
I have started to develop Project Vanquish, (an XNA, deferred rendering engine) but my shadows are not working correctly. I have been working for a week on it and can't figure out what is going wrong. I will be putting a 200 point bounty on this question, so if anyone solves the problem, I'll reward them. Source code is over at Codeplex too, grab the latest changeset.

I have the ShadowMap phase working, but the Shadow Occlusion stage doesn't appear to be working. At certain points, the debug RenderTarget will show the scene, but the scene is wrong. It shows black across the top with the outline of the model and nothing else.

```
protected void DrawShadowOcclusion(GraphicsDevice device, ICamera camera, RenderTarget2D depthTexture)
{
    // Set the device to render the shadow occlusion texture
    device.SetRenderTarget(shadowOcclusion);

    Matrix cameraTransform;
    camera.GetWorldMatrix(out cameraTransform);

    // Determine which split a pixel belongs too
    for (int i = 0; i < NUMBER_OF_SPLITS; i++)
    {
        lightClipPlanes[i].X = -splitDepths[i];
        lightClipPlanes[i].Y = -splitDepths[i + 1];
        lightCameras[i].GetViewProjectionMatrix(out lightViewProjectionMatrices[i]);
    }

    // Setup the shadow effect
    shadowEffect.CurrentTechnique = shadowOcclusionTechniques[(int)filteringType];
    shadowEffect.Parameters["g_matInvView"].SetValue(cameraTransform);
    shadowEffect.Parameters["g_matLightViewProj"].SetValue(lightViewProjectionMatrices);
    shadowEffect.Parameters["g_vFrustumCornersVS"].SetValue(farFrustumCornerVS);
    shadowEffect.Parameters["g_vClipPlanes"].SetValue(lightClipPlanes);
    shadowEffect.Parameters["ShadowMap"].SetValue(shadowMap);
    shadowEffect.Parameters["DepthTexture"].SetValue(depthTexture);
    shadowEffect.Parameters["g_vOcclusionTextureSize"].SetValue(new Vector2(shadowOcclusion.Width, shadowOcclusion.Height));
    shadowEffect.Parameters["g_vShadowMapSize"].SetValue(new Vector2(shadowMap.Width, shadowMap.Height));
    shadowEffect.Parameters["g_bShowSplitColors"].SetValue(false);

    // Begin the effect
    shadowEffect.CurrentTechnique.Passes[0].Apply();

    // Draw the FullscreenQuad
    fullscreenQuad.Draw();
}

```

Shader code:

```
//========================================================================
//
//  DeferredShadowMaps
//
//      by MJP  (mpettineo@gmail.com)
//      12/14/08
//
//========================================================================
//
//  File:       ShadowMap.fx
//
//  Desc:       Contains shaders used for generating and applying deferred
//              shadow maps.
//
//========================================================================

float4x4    g_matWorld;
float4x4    g_matWorldIT;
float4x4    g_matViewProj;
float4x4    g_matInvView;
float       g_fFarClip;
static const int NUM_SPLITS = 4;
float4x4    g_matLightViewProj [NUM_SPLITS];
float2      g_vClipPlanes[NUM_SPLITS];
float2      g_vShadowMapSize;
float2      g_vOcclusionTextureSize;
float3      g_vFrustumCornersVS [4];
bool        g_bShowSplitColors = false;
static const float BIAS = 0.006f;

texture DepthTexture;
sampler2D DepthTextureSampler = sampler_state
{
    Texture = <DepthTexture>;
    MinFilter = point;
    MagFilter = point;
    MipFilter = none;
};

texture ShadowMap;
sampler2D ShadowMapSampler = sampler_state
{
    Texture = <ShadowMap>;
    MinFilter = point;
    MagFilter = point;
    MipFilter = none;
};

// Vertex shader for outputting light-space depth to the shadow map
void GenerateShadowMapVS(in float4 in_vPositionOS   : POSITION,
                         out float4 out_vPositionCS : POSITION,
                         out float2 out_vDepthCS    : TEXCOORD0)
{
    // Figure out the position of the vertex in view space and clip space
    float4x4 matWorldViewProj = mul(g_matWorld, g_matViewProj);
    out_vPositionCS = mul(in_vPositionOS, matWorldViewProj);
    out_vDepthCS = out_vPositionCS.zw;
}

// Pixel shader for outputting light-space depth to the shadow map
float4 GenerateShadowMapPS(in float2 in_vDepthCS : TEXCOORD0) : COLOR0
{
    // Negate and divide by distance to far clip (so that depth is in range [0,1])
    float fDepth = in_vDepthCS.x / in_vDepthCS.y;

    return float4(fDepth, 1, 1, 1);
}

// Vertex shader for rendering the full-screen quad used for calculating
// the shadow occlusion factor.
void ShadowTermVS (in float3 in_vPositionOS             : POSITION,
                   in float3 in_vTexCoordAndCornerIndex : TEXCOORD0,
                   out float4 out_vPositionCS           : POSITION,
                   out float2 out_vTexCoord             : TEXCOORD0,
                   out float3 out_vFrustumCornerVS      : TEXCOORD1)
{
    // Offset the position by half a pixel to correctly align texels to pixels
    out_vPositionCS.x = in_vPositionOS.x - (1.0f / g_vOcclusionTextureSize.x);
    out_vPositionCS.y = in_vPositionOS.y + (1.0f / g_vOcclusionTextureSize.y);
    out_vPositionCS.z = in_vPositionOS.z;
    out_vPositionCS.w = 1.0f;

    // Pass along the texture coordiante and the position of the frustum corner
    out_vTexCoord = in_vTexCoordAndCornerIndex.xy;
    out_vFrustumCornerVS = g_vFrustumCornersVS[in_vTexCoordAndCornerIndex.z];
}

// Calculates the shadow occlusion using bilinear PCF
float CalcShadowTermPCF(float fLightDepth, float2 vShadowTexCoord)
{
    float fShadowTerm = 0.0f;

    // transform to texel space
    float2 vShadowMapCoord = g_vShadowMapSize * vShadowTexCoord;

    // Determine the lerp amounts
    float2 vLerps = frac(vShadowMapCoord);

    // Read in the 4 samples, doing a depth check for each
    float fSamples[4];
    fSamples[0] = (tex2D(ShadowMapSampler, vShadowTexCoord).x + BIAS < fLightDepth) ? 0.0f: 1.0f;
    fSamples[1] = (tex2D(ShadowMapSampler, vShadowTexCoord + float2(1.0/g_vShadowMapSize.x, 0)).x + BIAS < fLightDepth) ? 0.0f: 1.0f;
    fSamples[2] = (tex2D(ShadowMapSampler, vShadowTexCoord + float2(0, 1.0/g_vShadowMapSize.y)).x + BIAS < fLightDepth) ? 0.0f: 1.0f;
    fSamples[3] = (tex2D(ShadowMapSampler, vShadowTexCoord + float2(1.0/g_vShadowMapSize.x, 1.0/g_vShadowMapSize.y)).x + BIAS < fLightDepth) ? 0.0f: 1.0f;

    // lerp between the shadow values to calculate our light amount
    fShadowTerm = lerp(lerp(fSamples[0], fSamples[1], vLerps.x), lerp( fSamples[2], fSamples[3], vLerps.x), vLerps.y);

    return fShadowTerm;
}

// Calculates the shadow term using PCF soft-shadowing
float CalcShadowTermSoftPCF(float fLightDepth, float2 vShadowTexCoord, int iSqrtSamples)
{
    float fShadowTerm = 0.0f;

    float fRadius = (iSqrtSamples - 1.0f) / 2;
    float fWeightAccum = 0.0f;

    for (float y = -fRadius; y <= fRadius; y++)
    {
        for (float x = -fRadius; x <= fRadius; x++)
        {
            float2 vOffset = 0;
            vOffset = float2(x, y);
            vOffset /= g_vShadowMapSize;
            float2 vSamplePoint = vShadowTexCoord + vOffset;
            float fDepth = tex2D(ShadowMapSampler, vSamplePoint).x;
            float fSample = (fLightDepth <= fDepth + BIAS);

            // Edge tap smoothing
            float xWeight = 1;
            float yWeight = 1;

            if (x == -fRadius)
                xWeight = 1 - frac(vShadowTexCoord.x * g_vShadowMapSize.x);
            else if (x == fRadius)
                xWeight = frac(vShadowTexCoord.x * g_vShadowMapSize.x);

            if (y == -fRadius)
                yWeight = 1 - frac(vShadowTexCoord.y * g_vShadowMapSize.y);
            else if (y == fRadius)
                yWeight = frac(vShadowTexCoord.y * g_vShadowMapSize.y);

            fShadowTerm += fSample * xWeight * yWeight;
            fWeightAccum = xWeight * yWeight;
        }
    }

    fShadowTerm /= (iSqrtSamples * iSqrtSamples);
    fShadowTerm *= 1.55f;

    return fShadowTerm;
}

// Pixel shader for computing the shadow occlusion factor
float4 ShadowTermPS(in float2 in_vTexCoord          : TEXCOORD0,
                    in float3 in_vFrustumCornerVS   : TEXCOORD1,
                    uniform int iFilterSize)    : COLOR0
{
    // Reconstruct view-space position from the depth buffer
    float fPixelDepth = tex2D(DepthTextureSampler, in_vTexCoord).r;
    float4 vPositionVS = float4(fPixelDepth * in_vFrustumCornerVS, 1.0f);

    // Figure out which split this pixel belongs to, based on view-space depth.
    float4x4 matLightViewProj = g_matLightViewProj[0];
    float fOffset = 0;

    float3 vSplitColors [4];
    vSplitColors[0] = float3(1, 0, 0);
    vSplitColors[1] = float3(0, 1, 0);
    vSplitColors[2] = float3(0, 0, 1);
    vSplitColors[3] = float3(1, 1, 0);
    float3 vColor = vSplitColors[0];
    int iCurrentSplit = 0;

    // Unrolling the loop allows for a performance boost on the 360
#ifdef XBOX
    [unroll(NUM_SPLITS - 1)]
#endif
    for (int i = 1; i < NUM_SPLITS; i++)
    {
#ifdef XBOX
        [flatten]
#endif
        if (vPositionVS.z <= g_vClipPlanes[i].x && vPositionVS.z > g_vClipPlanes[i].y)
        {
            matLightViewProj = g_matLightViewProj[i];
            fOffset = i / (float)NUM_SPLITS;
            vColor = vSplitColors[i];
            iCurrentSplit = i;
        }
    }

    // If we're not showing the split colors, set it back to 1 to remove the coloring
    if (!g_bShowSplitColors)
        vColor = 1;

    // Determine the depth of the pixel with respect to the light
    float4x4 matViewToLightViewProj = mul(g_matInvView, matLightViewProj);
    float4 vPositionLightCS = mul(vPositionVS, matViewToLightViewProj);

    float fLightDepth = vPositionLightCS.z / vPositionLightCS.w;

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

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

    // Get the shadow occlusion factor and output it
    float fShadowTerm = 0;
    if (iFilterSize == 2)
        fShadowTerm = CalcShadowTermPCF(fLightDepth, vShadowTexCoord);
    else
        fShadowTerm = CalcShadowTermSoftPCF(fLightDepth, vShadowTexCoord, iFilterSize);

    return float4(fShadowTerm * vColor, 1);
}

technique GenerateShadowMap
{
    pass p0
    {
        ZWriteEnable = true;
        ZEnable = true;
        AlphaBlendEnable = false;
        FillMode = Solid;
        CullMode = CCW;

        VertexShader = compile vs_2_0 GenerateShadowMapVS();
        PixelShader = compile ps_2_0 GenerateShadowMapPS();
    }
}

technique CreateShadowTerm2x2PCF
{
    pass p0
    {
        ZWriteEnable = false;
        ZEnable = false;
        AlphaBlendEnable = false;
        CullMode = NONE;

        VertexShader = compile vs_3_0 ShadowTermVS();
        PixelShader = compile ps_3_0 ShadowTermPS(2);
    }
}

technique CreateShadowTerm3x3PCF
{
    pass p0
    {
        ZWriteEnable = false;
        ZEnable = false;
        AlphaBlendEnable = false;
        CullMode = NONE;

        VertexShader = compile vs_3_0 ShadowTermVS();
        PixelShader = compile ps_3_0 ShadowTermPS(3);
    }
}

technique CreateShadowTerm5x5PCF
{
    pass p0
    {
        ZWriteEnable = false;
        ZEnable = false;
        AlphaBlendEnable = false;
        CullMode = NONE;

        VertexShader = compile vs_3_0 ShadowTermVS();
        PixelShader = compile ps_3_0 ShadowTermPS(5);
    }
}

technique CreateShadowTerm7x7PCF
{
    pass p0
    {
        ZWriteEnable = false;
        ZEnable = false;
        AlphaBlendEnable = false;
        CullMode = NONE;

        VertexShader = compile vs_3_0 ShadowTermVS();
        PixelShader = compile ps_3_0 ShadowTermPS(7);
    }
}

```

By changing the `g_matInvView` line to :

```
shadowEffect.Parameters["g_matInvView"].SetValue(Matrix.Invert(cameraTransform));

```

I get:

# Answer
> 0 votes
The problem was with the `QuadRenderer` that I was using. The reason for the "lines" across the line image is because is was displaying the 4 shadow occlusions rather than displaying one fullscreen quad. I created a new class in order to cater for this and changed the `QuadRenderer` for this new class.

```
public class FullScreenQuad
{
    /// <summary>
    /// A struct that represents a single vertex in the
    /// vertex buffer.
    /// </summary>
    private struct QuadVertex
        : IVertexType
    {
        public Vector3 position;
        public Vector3 texCoordAndCornerIndex;
        public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration(
                new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
                new VertexElement(12, VertexElementFormat.Vector3, VertexElementUsage.TextureCoordinate, 0)
            );

        VertexDeclaration IVertexType.VertexDeclaration
        {
            get { return VertexDeclaration; }
        }
    }

    VertexBuffer vertexBuffer;

    /// <summary>
    /// Gets the quad's vertex buffer
    /// </summary>
    public VertexBuffer VertexBuffer
    {
        get { return vertexBuffer; }
    }

    /// <summary>
    /// Creates an instance of FullScreenQuad
    /// </summary>
    /// <param name="graphicsDevice">The GraphicsDevice to use for creating resources</param>
    public FullScreenQuad(GraphicsDevice graphicsDevice)
    {
        CreateFullScreenQuad(graphicsDevice);
    }

    /// <summary>
    /// Draws the full screen quad
    /// </summary>
    /// <param name="graphicsDevice">The GraphicsDevice to use for rendering</param>
    public void Draw(GraphicsDevice graphicsDevice)
    {
        // Set the vertex buffer and declaration
        graphicsDevice.SetVertexBuffer(vertexBuffer);

        // Draw primitives
        graphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);

        graphicsDevice.SetVertexBuffer(null);
    }

    /// <summary>
    /// Creates the VertexBuffer for the quad
    /// </summary>
    /// <param name="graphicsDevice">The GraphicsDevice to use</param>
    private void CreateFullScreenQuad(GraphicsDevice graphicsDevice)
    {
        // Create a vertex buffer for the quad, and fill it in
        vertexBuffer = new VertexBuffer(graphicsDevice, typeof(QuadVertex), QuadVertex.VertexDeclaration.VertexStride * 4, BufferUsage.None);
        QuadVertex[] vbData = new QuadVertex[4];

        // Upper right
        vbData[0].position = new Vector3(1, 1, 1);
        vbData[0].texCoordAndCornerIndex = new Vector3(1, 0, 1);

        // Lower right
        vbData[1].position = new Vector3(1, -1, 1);
        vbData[1].texCoordAndCornerIndex = new Vector3(1, 1, 2);

        // Upper left
        vbData[2].position = new Vector3(-1, 1, 1);
        vbData[2].texCoordAndCornerIndex = new Vector3(0, 0, 0);

        // Lower left
        vbData[3].position = new Vector3(-1, -1, 1);
        vbData[3].texCoordAndCornerIndex = new Vector3(0, 1, 3);

        vertexBuffer.SetData(vbData);
    }
}

```

---
Tags: xna, shadow-mapping
---


title: Ogre 3D Visibility Advice

text:
# Question
Title: Ogre 3D Visibility Advice
I would like an advice about some real-time rendering optimization. I'm rendering a BSP level, by only using the mesh, textures, entities, and lightmaps, not using VIS at all.

I'm trying to make my own Cell/Portal rendering system, a very basic one, but here is the problem, since Ogre uses a basic frustum culling (as I've heard), I think it would render everything behind the walls if every portals are in the field of view :

Do you have some better ideas to implement this ?

I am getting 650 FPS at a resolution of 1920x1080 if I render only zone only. I can get 1300 FPS if I see nothing.

Is 300 FPS good for a complex scene like this one?

I would like to make a lot of basic things clear for me.

# Answer
> 4 votes
Ogre3D actually comes with a scenemanager called PCZSM, the Portal Connected Zone Scene Manager, which is meant exactly for the purpose of portal-based occlusion culling. It should fit very well with your project. My usage experience is that it's very robust, although documentation is sparse - mostly it's in the form of forum posts.

---
Tags: c++, opengl, 3d, directx, ogre
---


# Question
Title: Player choices affecting a massive online world
Current generation MMOs are pretty static in that choices don't really affect the world for more than the scope of one or two quests -- but that doesn't give you a good sense of immersion, simply a temporary task.

I've had this idea of an MMO where whenever you make major decisions (such as burning down or sparing a village), you get teleported into an instanced version of the world with your changes (the village is burnt, the peasants are killed, etc) along with other players that have made the same choices.

The problem is that this requires a very large amount of instances, and players will be extremely fragmented and sparse throughout the world -- except in those areas that cannot be changed (for example, a central trading post.)

How do you solve this fragmentation problem, allowing more social interaction among players? It's hard to have an MMO with millions of players, each making different decisions.

# Answer
> 3 votes
What you could do is have certain quests that involve many people or require a certain number of people to complete it in order for something to happen. You could also have a counter-quest/decision that prevents it from happening (or causes something different).

Then, once the requirement has been met, you can change the world based on that for everyone. Then, you can just keep going with that storyline and add new quests based on it and make it part of the history of your world.

I know that some games do things like this but have "ages" or "epochs" whereby after say, one year, they reset the server and everything goes back to level one and the "world decisions" that were made are undone. Thus allowing people to make new decisions and see how they affect the world.

You could even make the trigger for the reset a huge end-game quest that involves all the players on the server. So that, unlike many MMOs, you can actually beat the game!

**Edit**

To address Lohoris's concerns (see comments), you could set up a system where the story for one "age" ends but a new story begins based on the world at that point. So if a city has been burned down because of a collection of player decisions, that city stays burned down, but maybe some pirates and bandits have moved into the ruins. Perhaps two ages later the players have the chance to rebuild the city. There's a lot you can do here.

Doing it this way, you give players the ability to control how the world and the game itself evolves. Which would increase the immersion factor immensely in my opinion.

# Answer
> 1 votes
I bet you want to have a look at A tale in the desert, and see what they did there.

Another idea could be thinking about it as something like Minecraft.

# Answer
> 0 votes
That would be a pretty peculiar world — one in which you are affected by your own decisions, but not (presumably with the exception of direct player–player interaction) by the decisions of anyone else.

Also, as you note, the world would get fragmented pretty quickly. Even with just a couple of dozen possible yes/no decisions, there would enough total combinations that pretty much each of your players would quickly end up in their own world shared by nobody else.

Some of the ways in which this *might* perhaps be made to work include:

* Severely limit the number of choices that trigger fragmentation, maybe only to one or two really big issues (like "start global nuclear war" vs. "don't start global nuclear war").
* Keep the fragmentation localized. So players who burned down the village and players who didn't would stay in the same world *except* when they enter the village. This might feel pretty weird — if you walk into the village with another player who didn't share your version of it, would they just disappear? — but then again, the whole concept is pretty weird to begin with.
* Allow player interaction between the instances, either on a meta-game level (e.g. through in-game chat channels) and/or directly in the game (e.g. by showing players in alternate instances as "ghosts" that can interact to a limited extent). The latter might work reasonably well with the "local realities" idea above.

All in all, this seems like a rather strange way to design a game, at least if taken at face value, and I suspect that "allowing more social interaction among players" is far from the only problem you'd face in trying to implement something like it. That said, I'd certainly like to see someone try this, if only for the weirdness factor.

# Answer
> 0 votes
It doesn't need to require too many instances. If you fragment the world into specific areas where choices are made (like that village being one fragment with a destroy/save choice) then you only have to make separate instances for that particular area. So you have a world fragmented into maybe 100 or so cells, where there are anywhere from 1 to 8 different instances for each are (0 choices to 3 choices). Plus if you get clever about the choices (such as not destroying the village out of mercy, and forcing the villagers to pay you to save the village) you could actually have more choices than instances. The biggest problem with this mode is that each area would have to load independently from one another; it would be kind of difficult to do a free-roaming MMO this way.

# Answer
> 0 votes
Recently, I've been thinking of way how to implement persistent world into MMO game. World where many players together would choose how to influence world and how to shape it. Of course that lesser changes would require less players with less power (influence). But to implement something like this in truly persistent world it would take immense amount of time and coders.

One way to bypass this problem is to make world reset after certain amount of time. This however is not taken enthusiastically by typical MMO players. They like to build their character. They want to build their power, to amass it. Server reset would upset pretty much all of them.

There is however one way how to let keep at least some if not all of their power regarding influencing world. My solution is to let them, right at the start, to create their own clan or lineage. Their character is then champion from their lineage and is representing it. Anything they do will either benefit or hinder their lineage. Well mostly benefit as we're talking about sort of building experience. And when server reset come and when there will be new age, players will simply choose new champion (create new character) from their lineage. They'll keep all their amassed influence and possibly more benefits (epic items, buildings generating money, rights...)

And that's basically it. I think this way will be both builders and explorers more or less satisfied. Of course we can't tell unless we try it, but it's sound good as concept to me.

---
Tags: game-design, mmo, level-design
---


# Question
Title: C# Console Snake Game, sort of fps problem
I have about 200 lines of code, really simple oop.

When I load the console game (snake), I don't see it running smooth, like fps problems in in games, but I don't understand why, because my files are a lot lighter and demand less resources than heavy games.

Thanks.

Linking my files to Pastebin

Main file: http://pastebin.com/60aeEBRa

SnakeObject.cs: http://pastebin.com/z0MPwNSA

Utilities.cs: http://pastebin.com/7jLDKUQ9

FoodObject.cs: http://pastebin.com/w1HuBQK4

RocksObject.cs: http://pastebin.com/QYcNbSad

Much thanks for your help.

I'm welcoming tips.

Thanks

# Answer
> 8 votes
You're doing a **lot** of `Console.SetCursorPosition` and `Console.Write` all over the place. The problem with this approach is that you'll be able to see the characters being drawn one by one, and even at a fast rate such as 16 updates per second, you will still be able to notice a lot of flickering because of this. In a graphics application this is what happens when you don't use *double buffering* \- you see the image being rendered instead of just seeing the complete picture.

The solution is simple, *render everything to a buffer*, and after everything is done, *write the complete buffer to the console in one go* at the end.

In your other question I explained how to do that, so I'll copy from there with a few optimizations:

```
// Create buffer to render to (create only once and store at class level)
char[][] render = new char[height][];
for(y=0; y<height; ++y)
    render[y] = new char[width];

// Clear buffer
for(y=0; y<height; ++y)
    for(x=0; x<width; ++x)
        render[y][x] = ' ';

// Render everything to buffer
map.Draw(render);
snake.Draw(render);
rocks.Draw(render);
food.Draw(render);

// Render to console
Console.Clear();
for(y=0; y<height; ++y)
    Console.WriteLine(render[y]);

```

All the other classes take the `render` buffer as a parameter to the `Draw` method, and rendering to it is as simple as doing, for instance:

```
render[2][2] = '#';

```

Notice that I also changed from using a multi-dimensional array (`name[,]`) to a jagged array (`name[][]`) in order to be able to pass each row as an individual array to `Console.WriteLine` (to the version that takes an array of chars).

# Answer
> 1 votes
This line from SnakeGame.Start() -method doesn't seem right:

```
System.Threading.Thread.Sleep((int)MS * 10);

```

At `MS` 's initial value ( 6.0 ) that line causes the main-thread to sleep 60ms every update, causing you game to run at ~16 fps at maximum.

---
Tags: c#
---


# Question
Title: What are the techniques used to save space with very large levels?
Some days ago I was thinking "how would I store the real world into a continuous game level ?".

I guess it must have been some challenge for RockStar engineers (for GTA 4 or Red Dead Redemption) or when developing RAGE (the ID game, not the rockstar engine), and I wonder how they solved it.

Of course current RAM and hard disk capacities don't allow it if you don't use high definition content, so you simplify by abusing the reuse of objects:

* Use doodads for trees, barriers, bushes, benches, trashbins, etc
* Use palettes instead of textures for the ground and walls and buildings
* Use heightmaps for altitude
* Use procedural method for modeling roads, houses, buildings, sidewalk, pavement
* Also use procedural methods to model the insides of buildings: walls, ceiling, stairs, doodads.

These are the only things which make sense to me, but I want to know if they are other methods I'm missing, like for example reducing vertex precision while storing models, but requiring to make an exporter.

# Answer
I use a template model. Every object in my game has a template ID, which is an integer. You can use the template ID to look up from a database or spreadsheet (or whatever you'd like), all the information about that kind of object. For example

```
Template ID     Name           Render Mesh          Physics Mesh
1               Pine Tree      Pine_Tree.nif        Pine_Tree_Phys.hkx
2               Wooden Crate   Wood_Crate.nif       Wood_Crate_Phys.hkx

```

Then all I store in my level files for each unique object is the template ID, position, rotation, scale, and optionally any custom data by using strings.

So if you have 2 trees and 1 crate in your level, the level file would look something like:

```
Template ID     Position           Rotation         Scale        Custom Data
1               (0, 1.5, 3.7)      (1, 0, 0, 0)     1.5          ""
2               (17.1, 3.2, 19.5)  (1, 0, 0, 0)     1.0          ""
1               (9.1, 52.4, 35.5)  (1, 0, 0, 0)     0.9          ""

```

Your level files should end up being relatively small by doing this. You could probably manage to pack the data even tighter if you placed all matching template IDs sequentially in your file so you didn't have to continue specifying template IDs for every matching entry. You could also compress the level files, uncompressing them only to load a level into memory (or parts of a level).

You can also break up your level files by physical locations within a level. For example if a level is very large then you could break up the level file into multiple smaller files, making each file easier to load into memory.

Heightmaps can be done fairly cheap. Generally only grayscale is required to get enough elevation detail for a map, so using a grayscale PNG file should keep the files fairly small, even for large maps.

Another technique is to scale your terrain horizontally. As you convert the heightmap image to actual vertices, multiply each X and Z coordinate by a scalar value (e.g. 4). Using a scalar of 4 would get you a terrain that is 4 times the size of your heightmap image. So if your heightmap image is 1024x1024 then your terrain will span 4096x4096 in the world. This allows you to have larger worlds, or the same size world with a smaller heightmap image. You lose detail on your heightmap as you scale, so I recommend finding the highest scale possible that is still an acceptable quality for your game.

If you're using texture splatting through an RGBA texture, to achieve multi-textured terrain, you can save on memory by breaking up the splatting texture into many smaller textures and using a RAW format instead. Let's say your terrain is 256x256, and your terrain can have up to 4 different textures that can overlap. By subdividing the splatting texture you may find that some of the 128x128 quadrants of the terrain only have 1, 2, or 3 textures in use in that section, so you can now store less information in those quadrants. If one quadrant only had 2 textures, for example, let's say using the Red and Green parts of the RGBA texture, then storing information for the Blue and Alpha for that quadrant would be a waste. So you break up the 256x256 texture for your terrain into four 128x128 raw files, and the quadrant using only Red and Green can now store only the raw data for those two colors, using nothing for the other two colors. If you use this method you also only have to load up the raw files for the portions of terrain that are visible, rather than the larger texture for the entire terrain all at once. Games like World of Warcraft use technology similar to this.
> 10 votes

# Answer
What most games do is break the map up into pieces that can be loaded dynamically.
> 1 votes

# Answer
Well there's many ways, simplifying the geometry.but also, that game is just huge. Also however, pieces are probably reused.
> 0 votes

---
Tags: architecture, procedural-generation, level-of-detail
---


# Question
Title: Apply Vertex Colors to XNA Spritebatch sprites
I know that you can use custom vertex and pixel shaders using SpriteBatch but I can't figure out how to apply colors to individual vertex points on a sprite generated by spritebatch. All I can do is apply a blanket color to the entire sprite rather than being able to blend between the 4 points that should be available in a quad. Can anyone give me a hand with this?

# Answer
**Edit - Changed to another solution that allows a source rectangle to be used.**

The color you choose when calling `SpriteBatch.Draw` is automatically stored in *all four* vertices of the quad. There's no way to change this behavior because it's done internally inside the `SpriteBatch`.

But there's a hack that you can use that relies on looking at the vertices' texture coordinates (which bu the way are automatically generated by `SpriteBatch` from your source rectangle and from the texture size) in order to identify *which* of the four vertices we're dealing with in the vertex shader, and then change its color before reaching the pixel shader.

I can think of many variations, but the trick I used was to pre-calculate what the texture coordinates would end up being at the *center* of the quad, so that in the vertex shader you can simply compare to see if the X and Y components are lower or higher than the center in order to determine which corner we're dealing with. You also need to pass it the color for each of the vertices, obviously. So here's the complete effect file code I used:

```
// Viewport size needed for VS
float2 ViewportSize;

// Vertex color
float4 TopLeftColor;
float4 TopRightColor;
float4 BottomLeftColor;
float4 BottomRightColor;
float2 CenterTexCoord;

void SpriteVertexShader(inout float4 color : COLOR0, inout float2 texCoord : TEXCOORD0, inout float4 position : POSITION0)
{
  // Half pixel offset for correct texel centering.
   position.xy -= 0.5;

   // Viewport adjustment.
   position.xy = position.xy / ViewportSize;
   position.xy *= float2(2, -2);
   position.xy -= float2(1, -1);

   // Determine which corner we're dealing with and set the corresponding color
   if(texCoord.x < CenterTexCoord.x)
   {
       if(texCoord.y < CenterTexCoord.y)
       {
           color = TopLeftColor;
       }
       else
       {
           color = BottomLeftColor;
       }
   }
   else
   {
       if(texCoord.y < CenterTexCoord.y)
       {
           color = TopRightColor;
       }
       else
       {
           color = BottomRightColor;
       }
   }
}

technique SpriteBatch
{
    pass
    {
        VertexShader = compile vs_2_0 SpriteVertexShader();
    }
}

```

And now the XNA side code. When you create the `Effect` you must let it know what the viewport size is, because it's needed by the vertex shader (in fact it's needed by any custom vertex created to be used with `SpriteBatch` because you need to do a viewport adjustment):

```
Effect _effect = Content.Load<Effect>("spriteBatchColorEffect");
_effect.Parameters["ViewportSize"].SetValue(new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height));

```

And when rendering I used the following code. Notice how I calculate the `CenterTexCoord` parameter from the source rectangle and the texture size:

```
Vector2 position = new Vector2(100, 100);
Rectangle source = new Rectangle(20, 20, 90, 90);

_effect.Parameters["TopLeftColor"].SetValue(Color.LightGreen.ToVector4());
_effect.Parameters["TopRightColor"].SetValue(Color.Yellow.ToVector4());
_effect.Parameters["BottomLeftColor"].SetValue(Color.Blue.ToVector4());
_effect.Parameters["BottomRightColor"].SetValue(Color.Red.ToVector4());
_effect.Parameters["CenterTexCoord"].SetValue(new Vector2((source.X + source.Width/2f)/_bg.Width, (source.Y + source.Height/2f)/_bg.Height));

_spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, _effect);
_spriteBatch.Draw(_bg, position, source, Color.White);
_spriteBatch.End();

```

And finally here's the result:

The best part is that there's no need for any pixel shader code - colors are automatically interpolated between vertices thanks to gouraud shading. This is the only solution I could come up with, but I'd be interested to know of a more proper way to solve the problem too.
> 2 votes

---
Tags: xna, vertex, color
---


title: 3D XNA Tracking Camera

text:
# Question
Title: 3D XNA Tracking Camera
I'm trying to implement a camera that tracks a 3D model in my game. I've taken a look at this MSDN article on creating a 3rd person camera, as well as experimenting on my own; but I don't get the correct result.

My camera follows behind my model correctly, until I rotate the model about the y-axis. In this case, the camera seems to fly off to one side or the other.

What I want, is when the model is rotated to the left the camera will remain behind it; so as too mimic the view that can been seen in the left image (minus the fact that the rest of the world will display the rotation). I have tried looking around for tracking camera implementations, but to no avail.

Here is the code I use to calculate the position and look-at vectors of the camera:

```
// Calculate the offset vector
Vector3 offset = new Vector3(0.0f, this.DistanceAboveTarget, -this.DistanceBehindTarget);

// Transform the offset by the target's rotation
float targetRotation = mTarget.Rotation.Y;
Matrix rotationMatrix = Matrix.CreateRotationY(targetRotation);

Vector3 transformedOffset = Vector3.Transform(offset, rotationMatrix);

// Calculate the new position and look at vectors
Vector3 targetPosition = mTarget.Position;
mLookAt = targetPosition;

mPosition = targetPosition + transformedOffset;

```

**EDIT**

All other matrices are calculate elsewhere in my code and are correct, so far as I understand. Full code samples can be found in the below links:

# Answer
**Attempt #1**

I couldn't find anything wrong with your camera class, but I found a few anomalies in your rendering code.

As far as I could tell, your calculations inside the camera class are correct. Further more, even if you were calculating the camera position wrong, since the `lookAt`parameter is set to match the character's position, I think the model *should* still appear centered in view no matter what, which is not the case here.

So I looked into your `GameModel` class and noticed some strange things. In particular these lines:

```
effect.World = mCamera.World;
effect.View = boneTransforms[mesh.ParentBone.Index] * modelViewMatrix;

```

You should almost certainly replace this with:

```
effect.World = boneTransforms[mesh.ParentBone.Index] * this.Transform;
effect.View = mCamera.View;

```

I'm unsure if this will solve the problem, since matrix multiplication is associative and it seems the resulting multiplication order will end up being the same as before, but give it a try. It doesn't really make sense to have a world matrix on your camera class anyway.

---

**Attempt #2**

Wait a minute, you're calculating the player position like this:

```
public Vector3 Position
{
    get { return mCenter + mTranslation; }
}

```

That extra `mCenter` might be the reason your camera is looking at the wrong spot. Your model should usually *already* be defined centered around local space, so there should be no need to add `mCenter` to the position.

And in case your model isn't centered, this still wouldn't be the correct way to do it. Let me know if that's the case and I'll guide you through the process. Basically you would need to calculate your world matrix a bit differently in order to account for an `Origin`, but that offset should happen *before* rotation, not together with translation. Something like:

```
Matrix transform = Matrix.CreateTranslation(-mCenter) *
                   Matrix.CreateScale(mScale) *
                   Matrix.CreateFromYawPitchRoll(mRotation.Y, mRotation.X, mRotation.Z) *
                   Matrix.CreateTranslation(mPosition);

```

And once again that's only if the model wasn't already centered when it was created.
> 1 votes

# Answer
The code you have gets the position of the camera but doesn't set the direction it's pointing. You didn't create the view or projection matrices yet (at least, not in your example code). Perhaps this is the problem. See the next steps in the MSDN article.

Here's the code (from the next two steps) that creates the view and projection matrices:

```
view = Matrix.CreateLookAt(cameraPosition, avatarPosition, new Vector3(0.0f, 1.0f, 0.0f));
Viewport viewport = graphics.GraphicsDevice.Viewport;
float aspectRatio = (float)viewport.Width / (float)viewport.Height;

proj = Matrix.CreatePerspectiveFieldOfView(viewAngle, aspectRatio,
nearClip, farClip);

```

Then, on the final step, you'll see that these get passed into the BasicEffect instance.
> 0 votes

# Answer
I'll break it down for you quickly. What you want to do is take the current `MouseState` and pass `MouseState` and use them to calculate the values you want to rotate around the X and Y axis by. Then create a rotation matrix by doing:

```
Matrix rotationMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(rotation)) * Matrix.CreateRotationY(MathHelper.ToRadians(rotation));

```

Then transform your third person reference (`Vector3` of the distance the camera is from player) by the new `rotationMatrix`.

Then change the camera position to the new transformed third person reference + your player position.

Lastly, change the `viewMatrix` to: `viewMatrix = Matrix.CreateLookAt(camera position, player position, Vector3.up);`.

That was just off the top of my head, but that's the gist of it.
> 0 votes

---
Tags: xna, c#, 3d, camera, third-person-view
---


title: 3d bounding Box border xna

text:
# Question
Title: 3d bounding Box border xna
So, I'm trying to develop a 3d table tennis game, and I'm having problems when it comes to colliding the ball with the table. I have a bounding sphere for the ball and bounding box for the table, but the intersection isn't that accurate, and I'm guessing that the bounding box is incorrect since colliding the ball with the racket is good.

I'm trying to display the bounding box so that it would be easier to see where the error is, but I cant seem to implement the tutorials I've found with my code, or just don't know how. And, I'm I right in creating an AABB since my table isn't moving? If anyone could help, it would be greatly appreciated, or if anyone could suggest a better way to collide a ball with a box (if there is) thanks. I've pasted my bounding box detection, and the collision between the sphere and box. If more code is needed I'll post it. Thanks

http://pastebin.com/NDYmhXCh

http://pastebin.com/47vwJWSc

# Answer
> 1 votes
Your code for creating the bounding box is correct, just make sure you're entering the correct world transform and off setting the position by whatever might have when you created it. Just keep debugging with break points, it's probably a small error in logic somewhere. Where are you calling the updateBoundingBox method from?

A quick tip, if you want to see if you created your aabb correctly without rendering it, just set your ball position to the aabb.max.X or aabb.min.Y or something like that inside the update method. That will show you the boundaries of the aabb without the need to create code for rendering.

# Answer
> 3 votes
Well, you're asking a few different questions there. I'll start by answering your main question which is about how to display a debug representation of a `BoundingBox` object.

**How to render a BoundingBox**

The easiest way I can think of is to get the corners of the bounding box and render it using a line list primitive. You can get the corners of the bounding box using the `BoundingBox.GetCorners()` method (documentation). This method returns 8 positions in world space. The first four represent the front face of the bounding box, and the final four represent the back face of the bounding box.

Then simply create a `VertexPositionColor` vertex for each of the corners, and render lines between them in the correct order. Whether you use indices or not is up to you.

No need to implement it though, just **download this sample** from the education catalog, add the `DebugShapeRenderer` class to your project, `Initialize` it and finally use the provided `AddBoundingBox` method. It does pretty much what I described above.

**Creating BoundingBox for the table**

> And am I right in creating an AABB since my table isn't moving?

That's subjective. If after checking it out with the debug drawing code above the bounding box is being calculated correctly, feel free to use it.

But personally, in this situation, I would just create the bounding box manually to allow more control over the collision area. Something like the following code (using 1 game unit = 1 cm as the scale):

```
class Table
{
    Vector3 size = new Vector3(152.5f, 274f, 5f);
    float height = 76f;
    Vector3 position = Vector3.Zero;

    BoundingBox boundingBox;

    public Table()
    {
        Vector3 min = position + Vector3.Up * height - size / 2f;
        Vector3 max = position + Vector3.Up * height + size / 2f;
        boundingBox = new BoundingBox(min, max);
    }
}

```

I find this approach much simpler overall.

**Better way to perform collisions**

> Or if anyone could suggest a better way to collide a ball with a box

I think incorporating a physics engine such as JigLibX (link) would yield better results and serve you better in the long run. The problem with most applications like this isn't collision detection, but collision response, and a physics engine really makes life much easier in that department.

---
Tags: xna, 3d, collision-detection, bounding-boxes
---


# Question
Title: Calculate impulse need on object to throw i Y meters into the air, with varying mass
Say I have an object that has a variable mass. Now I want to apply a vertical impulse (straight up into the air) onto the object, so it always flies up to the same height. How do I calculate this?

So the variables are:

```
m: mass
Y: height (constant)
If: Impulse force
G: Gravity

```

The origin is always from a floor, so no mid-air impulses or anything.

(I'm using the Box2D engine, but I think that a solution would be engine independent?)

# Answer
The potential energy of the object at its apex is m\*g\*h where g is the acceleration due to gravity, m is the mass of the object, and h is the height you want it to go to. We want the initial kinetic energy, 1/2\*m\*v^2 to be equal to the final potential energy. So we have

2\*m\*g\*h=m\*v^2

Impulse is defined as Force\*time, so F\*t=m\*a\*t, but under constant acceleration a\*t=v, so we have Impulse=m\*v. Solving for v and plugging in we have: 2\*g\*h=v^2=Impulse^2/m^2

Impulse=Sqrt(2gh)\*m.
> 4 votes

# Answer
it really depends on how long do you want to apply the force.

but for starter you can use `m*g*Y = f*dy` in which *f* is the force you are applying and *dy* is how far does the object travel before you stop applying the force (which usually is a small value for impulses)
> 0 votes

---
Tags: physics, box2d
---


# Question
Title: What are the current books for DirectX (w/ focus on 3D)?
For OpenGL, the OpenGL SuperBible 5th edition was just released only a few months ago, and is considered a fantastic, highly rated book for not only learning OpenGL 3 (Part 1 of the book), but it also goes into advanced OpenGL topics in Parts 2 and 3.

For DirectX, what is the current material we should be reading to learn? Books & websites with tutorials welcome. Are there any modern books available that go through the CURRENT version of DirectX that are intended for a beginning audience with a decent grasp of C++, but with no experience for DirectX at all?

This one seems to be highly praised : Introduction to 3D Game Programming with DirectX 10

# Answer
> 18 votes
Unlike OpenGL, which has a hodgepodge of tutorials, many vendors and implementations, and good but somewhat archaic (unless you're like me and enjoy reading man page style) reference documentation, DirectX has one implementation, and Microsoft maintains a good DirectX hub on MSDN.

Not that there aren't good books about DirectX, but many of these tutorials are equivalent in content and more up-to-date, e.g. the DirectX 11 tutorial and samples.

# Answer
> 13 votes
Frank Luna's books on DX9 and DX10 are really the only good books on Direct3D that I've seen. His DX11 book isn't due out until next year I think (it seems he had to find another publisher), but DX11 is close enough to DX10 as far as basic 3d graphics goes.

The only thing I'll say is that the title is a little bit misleading because there's no actual game programming in there - it is purely a graphics programming book.

UPDATE: It's worth noting that Frank Luna's DirectX 11 book is out now.

Just an update to this answer. Frank Luna's book are very good for learning DirectX where one doesn't need to cram the syntax and get the mathematical detail of everything what's going on.

Frank Luna's DirectX 12 book

# Answer
> 7 votes
If you want a solid and up to date textbook then I highly recommend Practice Rendering and Computation with Direct3D11. The book thoroughly covers all of the DirectX11 resources, the entire rendering pipeline, tessellation, DirectCompute, HLSL, multithreaded rendering, and then thorough discussions on common implementations of mesh rendering, dynamic tessellation, image processing, deferred rendering, simulations (using DirectCompute), and multithreaded paraboloid mapping.

It's a lot of information. Took me about half a year to work through. However, it doesn't leave my desk now while I'm working on my game.

# Answer
> 3 votes
Also make sure, if you do pick up a book, that it includes some chapters on the HLSL topic, as there is no more fixex pipeline in DX10+. Many books seem to not cover that subject at all, which is a big mistake IMO. The msdn is a great HLSL resource.

---
Tags: c++, directx
---


# Question
Title: Loading and unloading "chunks" of tiles in a 2d tile engine with 2d camera
I am making a 2d tile based game in C# and XNA 4.0. I am having trouble loading and unloading "chunks" of tiles(blocks). The whole world is randomly generated and is infinate on both axis. How would I go about loading and unloading chunks of tile data in the camera's view?

A pastebin to the pastebin links(I still have the 2 link cap):

http://pastebin.com/9PYr8cvC

# Answer
> 10 votes
Basically you want to have a range around your camera. When chunks come into this range, you load/generate them. When chunks leave this range, you save/unload. Keep in mind you'll want to keep the loaded range larger than the visible range, so your chunk loading isn't seen.

At the moment it looks like you're storing your chunks in a dictionary. That's kind of a strange choice, and it may be a little more work for you to maintain your chunks with that data structure.

It looks like you've got a lot of the functions you need already, nice work. You'll want a list of chunk positions that should be loaded, your loaded list. Your update loop is going to maintain that list. As the camera moves, you update the list to include all the chunks in the range of the camera.

This is where the dictionary choice is a little strange. Essentially you'd have to loop through all your dictionary entries, unload the chunks that aren't in your loaded list and load the ones that aren't in your dictionary but are in your loaded list. The alternative is to have some sort of linked list structure. Where you can add/remove chunks from either end. This does get a little tricky when dealing with 2D linked lists, but I think you can make it work.

It would look something like this:

Starting with this scenario, where the red dot is the camera, moving in the X plus direction. All the grid squares (chunks) touching the green area are currently loaded.

Then the camera moves far enough to get some new chunks:

All the blue chunks will be loaded/generated. All the red chunks will be unloaded/saved.

As for maintaining the list, you can update whenever the camera moves past a chunk boundary. Like if it moves past the X plus boundary of the chunk it's currently over, like in the example above, the chunks to be added or removed from the list could be found like this:

```
for(int y = Camera.Position.Y + LoadRange.Y; y >= Camera.Position.Y - LoadRange.Y; y--){
    AddToLoadedList(GetChunkRootPositionAt(Camera.Position.X + LoadRange.X, y));
    RemoveFromLoadedList(GetChunkRootPositionAt(Camera.Position.X - LoadRange.X, y));
}

```

Where `GetChunkRootPositionAt` converts a world position into the root position of the chunk that contains that location. And the `LoadedList` functions take a Vector2 to add/remove from the loaded list.

Finally, you may find adding in a buffer for unloading could be nice. If someone is moving the camera around a lot right on a chunk boundary, you can save a lot of loading/unloading by just keeping it loaded. Essentially, you may find that unloading at the same time as loading isn't necessarily the best option.

# Answer
> 1 votes
Find out how large your screen is and only render tiles that fall within that range. You might need a camera object to keep track of this data and some sort of x & y offset variables to keep track of movement around the world.

```
if(tile is inside of the window)
    render;

```

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


title: Getting fastest path on a grid

text:
# Question
Title: Getting fastest path on a grid
How would I go about finding the fastest path to connect two points on a grid? I'm making a 2D game and the map is based around a grid.

I need to be able to account for any blocked tiles that the path need be able to go through.

Example: https://i.stack.imgur.com/EHUTq.jpg
The blue line being what I need to figure out, and the red tiles being the blocked tiles.

Where should I start? Any advice be would great!

# Answer
Sounds like you want A-star path-finding, which is pretty much the defacto for path-finding. I used this in my XNA game: http://www.csharpcity.com/reusable-code/a-path-finding-library/ (I repackaged the library into a slightly more usable stand-alone DLL).
> 8 votes

---
Tags: xna, 2d, grid
---


# Question
Title: Correct way to "randomly" generate flowing terrain
I'm creating a simple top down RTS game. I plan on it "randomly" generating maps on the fly when I need to. I plan on it all working in 'passes':

1. Fill the terrain in with all grass
2. Go back and add some random spurts of gravel
3. Round out the gravel
4. Draw Mountain Landscape on second layer
5. Round out mountains
6. etc. etc.

Now, take a look at this picture below:

I hand created this using my map editor but I plan on this basically being the result after hopefully pass/step 3.

How should I go about deciding when and were to place my gravel so that it is at least irregularly shaped and sporadic enough to look natural?

Thanks if you can! Any and all help is appreciated!

**As a side note:**

Each pass is basically me iterating through all of my tiles (The map is divided into 40x40 tiles) similar to this:

```
for (int x = 0; x <= GRIDMAX - 1; x++) {
    for (int y = 0; y <= GRIDMAX - 1; y++) {
        //Terrain(x, y, 0) = SomethingHere;
    }
}

```

# Answer
> 5 votes
You can play around with Perlin Noise (see my StackOverflow answer for an implementation), to generate a height map. From the height map, you can map certain height ranges to different tiles. Something like:

* Top 20% Snow
* Next 20% Gravel
* Next 40% Grass
* Last 20% Water

You will have to play with the Perlin Noise generator values to get a terrain that can be generated and look nice.

# Answer
> 5 votes
As the others have said, perlin noise should be a good source of data for deciding where to place different types of tiles. I'd like to complement that idea and link two additional resources that should be helpful with with the third step in your checklist - **rounding the corners**.

This is a process called **auto-tiling** and it's not all that difficult to implement. There are many different ways to do it, but most of them rely on calculating adjacency information for each tile in order to decide which graphic should be drawn in that location.

A very elegant way to solve this problem is to assign a unique flag value to each adjacent tile direction, and lay out your spritehseet such that the value you get by adding together all the adjacent flags of a tile will correspond to the correct position of the tile in the spritesheet. Read **this article** for a very clear description of the technique.

And **here's another resource** which describes another variation of the technique.

# Answer
> 4 votes
Essentially you can use **Perlin Noise** generation to generate your maps. You would sample the height map generated and assign gravel blocks to parts of the map that have above a certain height.

Here is an excellent reference post on how to go about implementing such a system and different types of terrain that you could generate.

The examples have a lot more steps than you would need, but the concept is the same.

## More on Minecraft-type world gen

http://www.gamedev.net/blog/33/entry-2227887-more-on-minecraft-type-world-gen/

---
Tags: procedural-generation, terrain
---


title: How to Export Flash Animation Data

text:
# Question
Title: How to Export Flash Animation Data
I'd love for my partner, the artist, to be able to animate using flash movieclips and timelines. Then I, the programmer, would like to read the raw Flash info and re-program it into my engine of choice (which happens to be Torque2D). The data I'd want is

1. the bitmap images that were used in Flash, like the head and body
2. the links between the images, like where the head connects to the body
3. the motion data from the flash animation, like move, rotate (at what speed), shear, etc. for the head or arms or whatever.

Is there any way to get this data?

Here's what I know so far.

* There are tools like SWFSheet and Spriteloq that convert the entire flash animation into a frame by frame sprite animation (in a sprite sheet). This would take too much space in my case, so I'd like to avoid that. Re-animating on the fly would take much less texture memory.
* There is a PDF that describes the SWF file format but NOT the individual components like the movieclips.

So anyone know of a library I can use, or how I can learn more about the movieclip components and whatnot?

(more better tags: transform, export, convert)

# Answer
> 7 votes
I would recommend you to take a look at the grapefrukt exporter.

I didn't tried it myself yet (I will for sure!), but it seems to match your needs (well most of them).

Here is the list of features (from their website)

* Exports sprites to transparent pngs
* Exports MovieClips to animation sheets
* Parses positions of parts in MovieClips and exports keyframe data
* Exports sprites to SVG
* Exports fonts
* Data format defaults to XML but is fully customizable

There is a nice video presentation right on the website or here directly on YouTube

---

Edit: Here is an alternative solution, completely in opposition with the previous tool. But it may be interesting to know about it, even if **it does not fit your described needs** directly.

If you use Torque2D you probably use C++, so you can probably use external libraries to run SWF files directly into your project.

Here is a list of libraries of that kind:

# Answer
> 2 votes
**Followup:**

I'm still experimenting with Grapefrukt et al, but it looks like there may be an easier way!

Flash CS4 and greater supports a format for Flash projects called XFL. This format is very reader friendly and can probably be used to export data.

Classically, Flash had a project format known as FLA where all your source assets are combined into one big file. This includes your images, code, movieclips, vector graphics, etc. (It would be hard to work in a team on the same project and very hard to use source control).

With XFL, your project is kept as a directory of assets, similarly to other development tools. These assets include the movieclip information as XML data, the images, and the vector graphics as XML. Sweet!

---
Tags: flash, animation, sprites, graphics-programming, file-format
---


# Question
Title: Keeping track of onscreen objects in opengl es on Android
In a small game Im working on I was able to implement ray picking with an opensource 3d engine called min3d but I cant figure how to keep track of what object is onscreen. I will some times have upwards of 120 objects to render within my scene and the raypicking is off occasionally. What id like to do is keep track of how many screen objects are within the camera and being rendered onscreen and set a boolean value based on that to add or remove objects from my arraylist I iterate through when the screen touch is registered and the ray picking method goes off.

So how can I check for which objects are onscreen and offscreen in opengl es on android.

# Answer
> 3 votes
Your task is just get a polyhedron representing the view area, and check if your objects bounding boxes are inside it.

The blue are the near and far plane, the red and blue, together are a convex POLYHEDRON. Some engines give you helping methods to get this polyhedron. It's usually a pyramid(from camera to far plane), a trapezium(from near plane to far plane) or simply, a box for a orthographic projection. There are a lot of formulas about how to calculate if one box is inside a convex polyhedron on the web, This link is an awesome example.

I thought a little more, and other way, maybe cheaper to try this, is to calculate the angle between the object and the camera, see if it's withing fovy angle, farther than near plane, and nearer than far plane. Depending on how you do it, this could be cheaper but i'm not sure. Trig functions usually gets a great CPU time.

Some links to help you:

http://www.flipcode.com/archives/Frustum\_Culling.shtml \- Frustum culling is the technique that makes you don't draw what's outside the camera range. This link has how you can build a frustum bounding sphere, that may be very useful to you.
http://www.yaldex.com/game-programming/0131020099\_ch22lev1sec1.html \- Point inclusion, AABB tests and Point-in-Convex Polygon. To check if the object is inside the camera range.

---
Tags: android, opengl-es
---


title: GameCenter turn based central server

text:
# Question
Title: GameCenter turn based central server
I'm a tad confused about the turn based option with iOS5. Does this take care of everything needed to make a multiplayer turn based game?i.e all the game turn data is stored with apple or do I need to still provide a server for something?

# Answer
> 5 votes
You don't have to provide any server when using game center, if the player are close enough they **can** connect via bluetooth if not than they **will** be connected via internet through apples server for game center.

The only thing you need to do is to import the GameKit framework in your class and use appropriate methods to handle the events in your turn based game.

Also here are the links of the classes that you might use of game kit framework.

GKTurnBasedMatch\_Ref

GKTurnBasedEventHandler\_Ref

GKTurnBasedParticipant\_Ref

and here are some examples that will provide a good explanation for the game event handling.

GKRocket

GKTank

GKTapper

---
Tags: iphone, ios
---


# Question
Title: How do I know if a perspective matrix is right or left handed coordinate system?
For example, if I define my perspective matrix as the following:

```
m[0]  = 1.f / ( aspect * focalLength );
m[5]  = 1.f / focalLength;
m[10] = -zFar / (zFar - zNear);
m[11] = -1;
m[14] = -(zFar*zNear)/(zFar - zNear);

```

How can I tell if my perspective matrix is right or left handed coordinate system?

# Answer
I think you can tell the difference from whether you have 1 or -1 in the Z line (or column depending on the matrix orientation). In particular:

* Left handed: 1
* Right handed: -1

For a comparison, see both of these links - D3DXMatrixPerspectiveLH and D3DXMatrixPerspectiveRH. Since DirectX is left handed, you'd normally use the left handed version which has a 1 in the third row fourth column.

On the other hand, OpenGL and XNA are both right handed and I can confirm that the perspective matrices they generate use -1 instead, although OpenGL has it in the fourth row third column, whereas XNA has it in the third row fourth column like DirectX (column major matrices versus row major matrices).
> 7 votes

---
Tags: matrix, perspective
---


# Question
Title: How do I clear up artifacts between aligned faces when using AA in XNA 4.0?
I'm working on a graphics engine that lets you walk around a world that is made up of cubes (voxel engine) and I'm having some difficulties getting the results I want.

I'm not the best at 3D graphics, but I'm willing to learn. When I have anti-aliasing turned off, the textures line up properly together on the surfaces, but when I turn it on, I see a lot of lines between each square face. I've taken a picture:

I've tried changing the mip map mag filter options on the sampler, but cannot get it to look right. I've tried increasing the quality of the textures, but that doesn't help either. When I use Linear TextureFilter but that just makes everything super blurry, and the edges are even more obvious. In fact many edges get some blurry white and dark color to them. Anisotropic doesn't help.

Nothing I do seems to get rid of those lines in between faces when I have AA turned on. Anyone have any advice on where I would start looking? I'm assuming it's because all of the faces are individual, and not mixed together when they are next to each-other. Not just the edges are being anti-aliased. Not sure if I'm even on the right track with that thought.

I'm using XNA 4.0 to do this.

# Answer
Without seeing any code it's hard to guess, but here are two three major pitfalls to look out for:

1. On 3D graphics hardware, the edges of adjacent polygons are only guaranteed to align 100% **if their vertices are 100% the same**. So if you generate the vertices for each cube individually, and you use an algoritm that introduces tiny floating point errors... ****boom**** there could be tiny cracks all over the place at any time. Make sure to re-use vertices where possible, or at least re-use their `exact` floating point position.
2. Are the textures used for each cube subtextures? In that case, try setting the AddresU/AddressV `TextureAddressMode` to `Clamp`.
3. Are the textures used for each cube subtextures? Do the u,v coordinates match the exact corners of the subtexture without any additional padding? In that case, mipmapping is biting you. Especially the further-away tiles are sampled from the 2x downscaled mipmap, so your neatly fitting u,v coordinates now include part of the pixels from the adjacent area's (i.e. bleeding). As a quick test, assign a new sampler state and set

`state.Filter = TextureFilter.Point;`
> 3 votes

---
Tags: xna, voxels, antialiasing
---


title: b2Body moves without stopping

text:
# Question
Title: b2Body moves without stopping
I got a quite strange bug. It is difficult to explain it in two words, but i'll try to do this in short.

* My b2Body has restitution, friction, density, mass and collision group.
* I'm controlling my b2Body via setting linear velocity to it (called on every iteration):

```
(void)moveToDirection:(CGPoint)direction onlyHorizontal:(BOOL)horizontal {
    b2Vec2 velocity = [controlledObject getBody]->GetLinearVelocity();

        double horizontalSpeed = velocity.x + controlledObject.acceleration * direction.x;

        velocity.x = (float32) (abs((int) horizontalSpeed) < controlledObject.runSpeed
                ? horizontalSpeed
                : controlledObject.maxSpeed * direction.x);

        if (!horizontal)
        {
            velocity.y = velocity.y + controlledObject.runSpeed * direction.y;
        }

        [controlledObject getBody]->SetLinearVelocity(velocity);
    }

```
* My floor is static b2Body, it has as restitution, friction, density, mass and same collision group
* in some reason, I'm setting b2Body's friction of my Hero to zero when it is moving, and returning it to 1 when he stops.
* When I'm pushing run button, hero runs. when i'm releasing it, he stops. All of this works perfect.
* On jumping, I'm setting linear velocity to my Hero:

```
(void)jump {
    b2Vec2 velocity = [controlledObject getBody]->GetLinearVelocity();
    velocity.y = velocity.y + [[AppDel cfg] getHeroJumpVlelocity];
    [controlledObject getBody]->SetLinearVelocity(velocity);
}

```
* If I'll run, jump, and release run button, while he is in air, all will work fine.
* **And here is my problem:** If I'll run, jump, and continue running on landing (or when he goes from one static body to another: there is small fall, probably), Hero will start move, like he has no friction, but he has! I checked this via beakpoints: he has friction, but I can move left of right, and he will never stop, until i'll jump (or go from one static body to another), with unpressed running button.

## I already tried:

* Set friction to body on every iteration
* double-check am I setting friction to right fixture.
* Set Linear Damping to Hero: his move slows down on gugged moveing.

## A little more code:

### I have a sensor and body fixtures in my hero:

```
 (void) addBodyFixture
{
    b2CircleShape dynamicBox;
    dynamicBox.m_radius = [[AppDel cfg] getHeroRadius];

    b2FixtureDef bodyFixtureDef;
    bodyFixtureDef.shape = &dynamicBox;
    bodyFixtureDef.density = 1.0f;
    bodyFixtureDef.friction = [[AppDel cfg] getHeroFriction];
    bodyFixtureDef.restitution = [[AppDel cfg] getHeroRestitution];
    bodyFixtureDef.filter.categoryBits = 0x0001;
    bodyFixtureDef.filter.maskBits = 0x0001;
    bodyFixtureDef.filter.groupIndex = 0;
    bodyFixtureDef.userData = [NSNumber numberWithInt:FIXTURE_BODY];

    [physicalBody addFixture:bodyFixtureDef];
}

 (void) addSensorFixture
{
    b2CircleShape sensorBox;
    sensorBox.m_radius = [[AppDel cfg] getHeroRadius] * 0.95;
    sensorBox.m_p.Set(0, -[[AppDel cfg] getHeroRadius] / 10);
    b2FixtureDef sensor;
    sensor.shape = &sensorBox;
    sensor.filter.categoryBits = 0x0001;
    sensor.filter.maskBits = 0x0001;
    sensor.filter.groupIndex = 0;
    sensor.isSensor = YES;
    sensor.userData = [NSNumber numberWithInt:FIXTURE_SENSOR];

    [physicalBody addFixture:sensor];
}

```

### Here I'm tracking is hero in air:

```
void FixtureContactListener::BeginContact(b2Contact* contact)
{
    // We need to copy out the data because the b2Contact passed in
    // is reused.
    Squirrel *squirrel = (Squirrel *)contact->GetFixtureB()->GetBody()->GetUserData();
    if (squirrel)
    {
        [squirrel addContact];
    }
}

void FixtureContactListener::EndContact(b2Contact* contact)
{
    Squirrel *squirrel = (Squirrel *)contact->GetFixtureB()->GetBody()->GetUserData();
    if (squirrel)
    {
        [squirrel removeContact];
    }
}

```

### Here is Hero's logic on contacts:

```
- (void) addContact
{

    if (contactCount == 0)
        [self landing];
    contactCount++;
}
- (void) removeContact
{
    contactCount--;
    if (contactCount == 0)
        [self flying];
    if (contactCount <0)
        contactCount = 0;
}

- (void)landing
{
    inAir = NO;
    acceleration = [[AppDel cfg] getHeroRunAcceleration];
    [sprite stopAllActions];
    (running ? [sprite runAction:[self runAction]] : [sprite runAction:[self standAction]]);
}
- (void)flying
{
    inAir = YES;
    acceleration = [[AppDel cfg] getHeroAirAcceleration];
    [sprite stopAllActions];
    [self flyAction];
}

```

### Here is Hero's moving logic:

```
- (void)stop
{

    running = NO;
    if (!inAir)
    {
        [sprite stopAllActions];
        [sprite runAction:[self standAction]];
    }
}

- (void)left
{
    [physicalBody setFriction:0];
    if (!running && !inAir)
    {
        [sprite stopAllActions];
        [sprite runAction:[self runAction]];
    }
    running = YES;
    moveingDirection = NO;
    [bodyControls moveToDirection:CGPointMake(-1, 0) onlyHorizontal:YES];
}

- (void)right
{
    [physicalBody setFriction:0];
    if (!running && !inAir)
    {
        [sprite stopAllActions];
        [sprite runAction:[self runAction]];
    }
    running = YES;
    moveingDirection = YES;
    [bodyControls moveToDirection:CGPointMake(1, 0) onlyHorizontal:YES];
}
- (void)jump
{
    if (!inAir)
    {
        [bodyControls jump];
    }
}

```

### And here is my update method (called on every iteration):

```
 - (void)update:(NSMutableDictionary *)buttons
    {
        if (!isDead)
        {
            [self updateWithButtonName:BUTTON_LEFT inButtons:buttons whenPressed:@selector(left) whenUnpressed:@selector(stop)];
            [self updateWithButtonName:BUTTON_RIGHT inButtons:buttons whenPressed:@selector(right) whenUnpressed:@selector(stop)];
            [self updateWithButtonName:BUTTON_UP inButtons:buttons whenPressed:@selector(jump) whenUnpressed:@selector(nothing)];
            [self updateWithButtonName:BUTTON_DOWN inButtons:buttons whenPressed:@selector(nothing) whenUnpressed:@selector(nothing)];
            [sprite setFlipX:(moveingDirection)];

        }

        [self checkPosition];
        if (!running)
            [physicalBody setFriction:[[AppDel cfg] getHeroFriction]];
        else
            [physicalBody setFriction:0];
    }

- (void)updateWithButtonName:(NSString *)buttonName inButtons:(NSDictionary *)buttons whenPressed:(SEL)pressedSelector whenUnpressed:(SEL)unpressedSelector
{
    NSNumber *buttonNumber = [buttons objectForKey:buttonName];
    if (buttonNumber  == nil)
        return;

    if ([buttonNumber boolValue])
        [self performSelector:pressedSelector];
    else
        [self performSelector:unpressedSelector];
}

- (void)checkPosition
{
    b2Body *body = [self getBody];
    b2Vec2 position = body->GetPosition();
    CGPoint inWorldPosition = [[AppDel cfg] worldMeterPointFromScreenPixel:CGPointMake(position.x * PTM_RATIO, position.y * PTM_RATIO)];
    if (inWorldPosition.x < 0 ||
        inWorldPosition.x > WORLD_WIDGH / PTM_RATIO ||
        inWorldPosition.y <= 0)
    {
        [self kill];
    }
}

```

# Answer
I needed only reset friction on presolve:

```
void FixtureContactListener::PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
    contact->ResetFriction();

}

```
> 2 votes

---
Tags: box2d, cocos2d-iphone, objective-c
---


title: help a 2D image onto a 3D cube

text:
# Question
Title: help a 2D image onto a 3D cube
I am just diving into the Stage3D APIs for Flash Player 11. I am trying to figure out a simple way to display isometric 2D content that gets blitted from a sprite sheet onto a 3D cube. The idea being that then the isometric content can be split into the appropriate quads of the cube and handed over to the GPU.

I found this post 2D sprites in 3D space? but I don't understand if the billboard method would split the content properly to ensure depth sorting of the quads.

Are there algorithms for basically projecting the image into the respective quads?

**Addition Info** (added 2012.03.06 @ 1124 GMT -6)

If you were to overlay a 3D box projected isometrically on top of a 2D isometric sprite (say a crate), the faces of the box (i.e. the top, left & right) should line up roughly with the perceived edges of the 2D sprite. I want to chop up the 2D sprite along those edges and apply them to the 3 quads (again the top, left and right faces of the 3D cube).

I'd assume there is some pretty gnarly translations to skew the 2D content to fit that quads yet maintain their perspective when viewed via an iso camera in 3D.

# Answer
You need to learn about UV mapping. For that you'll have to provide UV coordinates with your vertex data. This introduction to stage3D also covers how to use textures and specify UV coordinates (at about 2/3 of the page).

To map a portion of a sprite-sheet to a quad, you have to calculate the UV coordinates for that portion. Imagine your texture is `256 x 256` and you wish to map a sprite with the dimensions of `32 x 32`, located at `32, 64` to a quad. Since the texture width and height always maps to `0..1`, you calculate the coordinates as follows:

```
  U: 1 / 256 * 32, V: 1 / 256 * 64
 /
+----------+
|          |
|          |
|          |   U: 1 / 256 * 64, V: 1 / 256 * 96
|          | /
+----------+

```

So the UV coordinate for the top-left vertex would be `0.125, 0.25` and `0.25, 0.375` for bottom right. Knowing this, it should be simple to calculate the UVs for all the vertices (assuming you're just dealing with simple quads). Calculating good UVs for arbitrary meshes can of course be very complicated, that's why UV coordinates are usually generated by artists when the "unwrap" a model in a 3D modelling package.
> 2 votes

---
Tags: 2d, 3d, flash, isometric, spritesheet
---