# Question
Title: Algorithm to produce 'Lady or Tiger' puzzles?
**What my problem is:**

There is a puzzle by Raymond Smullyan that works something like this: You are in a room with many doors. Behind some of those doors, there are ladies; behind the others, there are tigers. Your goal is to pick one of the right doors (the ones with the ladies). On every door, there's a sign that says something like *There's a lady behind this door* or *There is a lion behind door II and VI* and so on. Now, you also have some additional information like *Only one of the signs says the truth* or *The sign on a door is true only if there is a lady behind that door* and so on. For example, the first puzzle goes like this:

> There are two doors with one sign each. One of the signs is true, the other one is false:
>
> ```
>  ---------------------    ---------------------
> |      DOOR I         |  |      DOOR II        |
> | There's a lady in   |  | In one of those     |
> | this room and a     |  | rooms, there's a    |
> | a tiger in the      |  | lady, in the other  |
> | other one           |  | one there's a tiger |
>  ---------------------    ---------------------
>
> ```
>
> Behind which door is a lady?

Now, getting to the topic of this question: I'm looking for possible ways to auto-generate such puzzles. The (far away) goal is to build an algorithm that requires, as parameters, the number of doors (and maybe the difficulty of the resulting puzzle) and creates corresponding texts for the doors.

**What I have tried so far:**

Not much, as I don't really know where to start. It's easy to create a pattern for the text on the signs and it's also easy to randomly assign true and false statements to those signs, corresponding to the true-false-rule you use (e.g. *Only one sign says the truth*). But that's the part where it get's tricky: How to create a puzzle that is **solvable** and has a **unique solution**? My first idea was to create a random puzzle and use backtracking to search for solutions. But that way, it could take very long until the algorithm has finally found a working set of signs. Also, that way you can't easily determine how difficult a given puzzle is.

So, summing it up: Do you have any idea, any helpful links, etc.? Any help is appreciated, I don't expect anyone to post a perfect and complete solution for my problem.

*(Note: I originally asked the following question on stackoverflow but was told there that I would be more likely to get an answer here!)*

# Answer
Text generation is a separate issue, but for a small number of doors perhaps you could use a Karnaugh map. Pick a random cell that will be true, all others will be false, then use an appropriate algorithm to find the most efficient boolean expression that matches that map, e.g.

http://www.codeproject.com/Articles/37031/Karnaugh-Map-Minimizer-3-Variables
> 1 votes

---
Tags: algorithm, puzzle
---


# Question
Title: How do I apply different probability factors in an algorithm for a cricket simulation game?
I am trying to write the algorithm for a cricket simulation game which generates runs on each ball between 0 to 6. The run rate or runs generated changes when these factors come into play like skill of the batsman, skill of the bowler, target to be chased. Wickets left.

If the batsman is skilled more runs will be generated. There will be a mode of play of the batsman aggressive, normal, defensive. If he plays aggressive chances of getting out will be more. If the chasing target is more the run rate should be more. If the overs are final the run rate should be more.

I am using java random number function for this. The code so far I've written is

```
    public class Cricket {

public static void main(String args[])
{
    int totalRuns=0;
  //i is the balls bowled
     for (int i = 1; i <= 60 ; i++)
       {
        int RunsPerBall = (int)(Math.random()*6);
        //System.out.println(Random);
        totalRuns=totalRuns+RunsPerBall;
       }
    System.out.println(totalRuns);
}

    }

```

Can somebody help me how to apply the factors in the code. I believe probability will be used with this. I am not clear how to apply the probability of the factors stated above in the code.

# Answer
You can work your way backwards by creating a series of grids and calculating the stats for each grid.

Imagine for example 16 balls being bowled at a player (4 down the leg side, 4 down the off side and eight on target and the expected outcome for each one (ignoring dot balls where no runs are scored or wickets taken):

**a) Batsman vs Poor Bowler**

```
6 1 1 1    <-- Full Toss
1 2 1 1    <-- Overpitched
1 W 1 1    <-- Good Length
1 1 1 4    <-- Short of a length

```

total runs = **24** outs = **1** bowler's strike rate is **16** \- batsman's average = **24** Run Rate=1.5

**b) Batsman vs Medium Bowler**

```
6 1 1 1
1 2 W 1
1 W 2 1
1 1 1 4

```

total runs **24** outs= **2** bowler's strike rate is **8** \- batsman's average = **12** Run Rate=1.5

**c) Batsman vs Good Bowler**

```
W 1 2 1
1 2 W 1
1 W W 1
6 2 2 4

```

total runs = **24** outs = **4** bowler's strike rate **4** batsman's average = **6** Run Rate=1.5

So for a NxN grid

* The bowler's strike rate is `N * N/Number of Wickets in grid` (excluding stumpings)
* The batting average is `Number of Runs in grid/ Number of Wickets in grid`
* The run rate is `Number of runs in grid/ N * N`

Now if all batsmen were of equal quality, you could choose between grid a) grid b) and grid c) based on the strike rate of the bowler, if the bowler has an average of 16 then always use grid a), if the bowler has an average 12 then half the time chose a) and half the time b) etc.

You can change the quality of the batsman in the same way, e.g. by reducing the number of runs within the grid:

**d) Poor Batsman vs Poor Bowler**

```
1 1 1 1
1 2 1 1
1 W 1 1
1 1 1 1

```

total runs = **16** outs= **1** bowler's strike rate **16** batsman's average = **16** Run Rate=1

**e) Poor Batsman vs Medium Bowler**

```
1 1 1 1
1 2 W 1
1 W 1 1
1 1 1 2

```

total runs = **16** outs = **2** bowler's strike rate **8** batsman's average = **8** Run Rate=1

**f) Poor Batsman vs Good Bowler**

```
2 1 1 1
1 W 1 1
1 W W 1
1 1 W 4

```

total runs = **16** outs= **4** bowler's strike rate **4** batsman's average = **4** Run Rate = 1

You could also **increase** aggression i.e. **increase** the run rate & strike rate simultaneously by **reducing** the number of dot balls per over.
> 1 votes

# Answer
Note: Never played cricket.

I would use multipliers. Multiply your randomly generated number by values based on player skill and mode of play. These numbers will be close to 1 (~.5 - 2). Compiling several multipliers may be tricky (`5 * .8 * 1.2 != 5`).

Going out may been a true/false state with a threshold. Random 0-1 and if over X then they go out. Repeat for each way to go out. Set the threshold based on skill and mode of play. Or each way to go out has a baseline threshold which is multiplied by another set of multipliers.

Deciding these multipliers may be difficult. If you are using real people, you could find a way to convert their season stats to these multipliers.

Also don't use `(int) double` for converting from a decimal value to an integer. I truncates the value(4.2 and 4.8 both round to 4). They are multiple ways to round in Java; the most common is `Math.round()`.
> 0 votes

# Answer
One option is to calculate a positive number based on the chance of each event happening, for each ball bowled. Here's some examples, with some randomness and weightings thrown in. You can get away without randomness in this part if you want to:

```
Chance of being out = max(0, (rand() % BatsmanSkill) - (rand() % (BowlerSkill + BatsmanAggression)))
Chance of scoring 6 = max(0, (rand() % (BatsmanSkill + (BatsmanAggression * 2))) - (rand() % (BowlerSkill)))
Chance of scoring 4 = max(0, (rand() % (BatsmanSkill + (BatsmanAggression))) - (rand() % (BowlerSkill)))
// TODO: Fill in 5, and 0-3, and other influences on the outcome

```

Once you have all the numbers, you can then randomly pick between them based on their weights:

```
Outcome = rand() % sum_of_chances;
if (Outcome <= Chance of being out) BatsmanIsOut();
else if (Outcome <= Chance of being out + Chance of scoring 6) Score(6);
// etc.

```

The tricky bit comes in tuning the numbers to make the game play well.
> 0 votes

# Answer
The strategy pattern seems like it'd be a good fit here. It's a way to change algorithms interchangeably at runtime.

I recommend reading up on it via its Wikipedia article or watching the PatternCraft video on the subject:

http://www.youtube.com/watch?v=MOEsKHqLiBM

(The language in the video uses ActionScript, but it is easily translated to any language)
> 0 votes

---
Tags: java, algorithm, probability
---


# Question
Title: How to determine character's foot contact point on a uniform triangle mesh terrain?
For a terrain that is modelled by a heightmap with a uniform triangle mesh, what are some techniques I could use to determine the contact point of the foot of a character standing on the terrain?

Since the terrain's Y values are altered by the heightmap, they won't be flat any more. As the character moves on the terrain, it has to know at which values of Y-value its foot should be. Conceptually, what are some methods and techniques to determine the contact point of the character's foot standing on the terrain?

# Answer
> 1 votes
While the topic can be quite bi,g I will summarize the process in 3 steps. I will try to be concise:

### Identify the set triangle(s) that your character is likely be standing on (Broad phase)

This is a classic problem in collision detection, which is identifying the possible collisions (also called **broad phase**) in your world instead of checking for each pairs (the character and every triangle in your case).

The problem lays in the usually huge number of possible collisions, for example if your terrain consists of 1 million triangles, then here is one million checks just to know which triangle the character is standing on.

The good news is, such cases are typically solved by **exploiting the spatial coherency** of the world, closer object are more likely to hit each other than farther away objects. A classic implementation of such an idea is typically some kind of spatial data structures like uniform grids, kd-trees, and octrees. These will potentially narrow down the number of collision tests from O(n^2) to O(n), which (loosely speeking) most likely be "few number" of intersection tests.

I want to add, that in case your terrain triangles count or number of objects are small it's ok to use brute force which will take O(n^2), since it's "fine" for small sets.

### Check ray intersection with the potential triangles

Once you identified the potential triangles, you need to perform intersection test, from a ray that is dropped down from your character with the potential set of triangles, and calculate the intersection point.

### Calculate character standing height

Once you calculate the intersection point, you can do one of two things, depending on the situation:

* Directly use the "Y" of the calculated intersection point to adjust the standing point of your character.
* Use bi-linear interpolation, in case your character is still in the same cell, and is intersecting with the same set of triangles, to calculate the height and adjust the character's position.

# Answer
> 0 votes
First, you need to identify the triangle in your heightmap. Then you must find the point of intersection between the triangle's plane and the line that drops down vertically through it.

If you want more explanation, maybe this post will help.

---
Tags: terrain, heightmap
---


# Question
Title: How does Apple use App Store image banners?
I am about to publish my very first iOS game and was reading the Apple iTunes Connect guide (pages 237 till page 240). I understand that they require a PSD file of dimension 3200x600 pixels. I also understand that this image will be cropped in order to fit the desktop, iPad and iPhone store aras, along with a "minimal view" version.

How, what I don't understand is:

* Do they ever scale the image? I've never seen a high resolution banner in the iPhone Editor's choice images. The iPhone specs are about 640x960 or 640x1136 pixels and the width of the iPhone image area in the guide seems much higher, so that's why I assume the rescale it.
* How do they obtain the "Extreme Skater" 150px300px image on the left, below? Is that simply the title rescaled on a portion of the background? There is no mention of how they do this in the guide.

I imagine that the one on the right is the one obtained from the iPhone area of the editor's choice banner creation guideline, but haven't found any specs on how to obtain the other image.

How does the Apple measuraments relate to the view I can see here (it is taken from an iPod touch 4th generation with retina display and measured using the rectangle selection on the Mac OS X Preview tool)

# Answer
The guide defines, as a subset of the "minimum view" area, a "title-safe" region and a "tag area." The title-safe region appears to be what is used to create the small banner that appears in the bottom right of your left-hand screenshot.

I do not believe they ever re-scale the artwork, they just crop it according to their needs. Remember that Apple wants this artwork to display on retina (effectively double-density) screens, so what appears to be a 150x300 pixel image is really a 300x600 pixel image, which fits with their artwork metrics as called out in the guide.

Part of the reason Apple's guidelines for exact pixel dimensions are loose is likely because they want to reserve the right to redesign how they present your artwork within their stores without having to get *new* artwork for all applications. Thus, their guidelines tell you the minimum area you will get (that title safe area), and the rest you have to assume will be dead space (and so you shouldn't put anything super important there).
> 1 votes

---
Tags: ios, appstore
---


# Question
Title: How should I attenuate sound in a 2D game where you can zoom in and out?
In my 2D game, I have some ambient sounds like the noise of a waterfall or the humming of a generator. However, it is not practical to play these sound all the time at full volume as in a large level the overlap of many of such noises would be quite unpleasant to the ear.

I am currently thinking about a system that modulates the volume of certain sounds depending on their distance to the player. However, this is partly not a great solution as (for example) in a zoomed state the player might be quite far away from the sound source (like a water fall) but still be able to see it on screen but not hear it (due to the distance) which is quite awkward.

Is there a solution for such a problem?

# Answer
I think you are on the right track. Your proposed system of distance-based attenuation should work if you

* always use the in-game distance to the object from the player, which remains fixed regardless of the zoom level (don't use the "on-screen" distance, which changes as you zoom) and
* set up your attenuation system to begin playing an object's sounds as soon as its distance to the player in the world is such that the object would *almost* be visible to the player at the maximum zoom level.

This way players can hear things before they see them, which imparts a sense of realism and discovery. It also prevents most scenarios of playing too many ambient sounds.

Of course, you still have the potential to overload the ambient sound channel if you happen to have a lot of sound-emitting objects in the same spot in the world. This can be solved by

* designing your levels not to do that, or, if that's not viable,
* giving objects a sound priority, and taking only the top `n` highest-priority objects, or
* modulating down the volume of all ambient sounds by (more or less) "dividing by the number of sounds in the scene," making sure that you still smoothly fade out sounds as their objects become further away in order to avoid "popping" as you discretely jump from five objects to four, for example.
* precompute, for a given level or the whole game, the maximum number of objects that can be in-range and playing sounds at once (do this as part of the level or game data build process). Based on that you can determine how loud to play any one object such that the worst-case never exceeds a certain volume.

The latter two options address the problem *purely* from a volume perspective, however -- they don't account for the fact that even if you play 500 background sounds quietly enough not to overwhelm a player's eardrums, you are still playing 500 sounds, which can be *noisy* not in the volume sense but in the confusing sense.

To handle that problem, I think you are best off trying to reduce the total number of ambient emitters or taking only the top `n` prioritized sounds (for reference, taking the top `n` is more-or-less what we settled on for Guild Wars 2).
> 7 votes

---
Tags: 2d, xna-4.0, sound, audio, sound-effects
---


# Question
Title: When is the Z coordinate normalized in GLSL?
I thought that whenever you transform an object to world space, then view space and finally screen space, the last matrix you apply(the projection matrix) normalizes the z values between 0 and 1.

However, I'm getting big z coordinates, which implies that the projection matrix didn't normalize it. Am I doing something wrong? I mean, all I do is:

```
gl_Position = projection * view * world * gl_Vertex;

```

# Answer
You are missing a few key points.

After the application of the projection matrix, you have a 4-component vector in *clip space* (not screen space), which is a homogeneous coordinate system in which clipping will be performed (after your vertex shader).

After clipping, the surviving coordinates are divided by the `w` component to get normalized device coordinates in (-1, 1). A transformation will then be applied to move from NDC space to window coordinates, where the X and Y coordinates are normalized based on the viewport provided to OpenGL and the Z coordinate is normalized based on the depth range, which is ultimately what gives you your (0, 1) range for depth (unless you use `glDepthRange` to set a different range).

If you want to access this normalized Z value in your vertex shader, you will need to do the computation manually in the shader (based on the information above).
> 13 votes

# Answer
Multiplying a vertex position by the world, view, and projection matrices generates a position in homogeneous coordinates, i.e. (x, y, z, w). Only after dividing by w are the xyz values between -1 and 1 (note: not 0 to 1).

If you're not familiar with homogeneous coordinates, see these other questions on this site: What does the graphics card do with the fourth element of a vector? and Do I need the 'w' component in my Vector class?
> 2 votes

---
Tags: opengl, shaders, graphics, glsl
---


# Question
Title: Setting up OpenGL camera with off-center perspective
I'm using OpenGL ES (in iOS) and am struggling with setting up a viewport with an off-center distance point.

Consider a game where you have a character in the left hand side of the screen, and some controls alpha'd over the left-hand side. The "main" part of the screen is on the right, but you still want to show whats in the view on the left. However when the character moves "forward" you want the character to appear to be going "straight", or "up" on the device, and not heading on an angle to the point that is geographically at the mid-x position in the screen.

Here's the jist of how i set my viewport up where it is centered in the middle:

```
// setup the camera
    //

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    const GLfloat zNear = 0.1;
    const GLfloat zFar = 1000.0;
    const GLfloat fieldOfView = 90.0; // can definitely adjust this to see more/less of the scene

    GLfloat size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);
    CGRect rect;
    rect.origin = CGPointMake(0.0, 0.0);
    rect.size = CGSizeMake(backingWidth, backingHeight);
    glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size / (rect.size.width / rect.size.height), zNear, zFar);

    glMatrixMode(GL_MODELVIEW);

    // rotate the whole scene by the tilt to face down on the dude
    const float tilt = 0.3f;
    const float yscale = 0.8f;
    const float zscale = -4.0f;
    glTranslatef(0.0, yscale, zscale);
    const int rotationMinDegree = 0;
    const int rotationMaxDegree = 180;

        glRotatef(tilt * (rotationMaxDegree - rotationMinDegree) / 2, 1.0f, 0.0f, 0.0f);

    glTranslatef(0, -yscale, -zscale);

    static float b = -25; //0;
    static float c = 0;

    // rotate by to face in the direction of the dude
    float a = RADIANS_TO_DEGREES(-atan2f(-gCamera.orientation.x, -gCamera.orientation.z));
    glRotatef(a, 0.0, 1.0, 0.0);

    // and move to where it is
    glTranslatef(-gCamera.pos.x, -gCamera.pos.y, -gCamera.pos.z);

    // draw the rest of the scene
    ...

```

I've tried a variety of things to make it appear as though "the dude" is off to the right: \- do a translate after the frustum to the x direction \- do a rotation after the frustum about the up/y-axis \- move the camera with a biased lean to the left of the dude

Nothing i do seems to produce good results, the dude will either look like he's stuck on an angle, or the whole scene will appear tilted. I'm no OpenGL expert, so i'm hoping someone can suggest some ideas or tricks on how to "off-center" these model views in OpenGL. Thanks!

# Answer
> 3 votes
Typically when working with a camera system, in addition to the frustum, you need three other pieces of information: where the camera is (eye), what it's pointed at (at), and its orientation (up). When trying to solve your shoulder-view problem, it is not typical to be modifying the frustum. You should set the camera at that shoulder view by modifying "eye." To get it to look like he is walking in a straight line, I would try making the camera look along a vector that is parallel to "the dude's" vector of movement in order to make it look like he is moving in a straight line, and that is done by modifying "at." If you need to make your scene look wonky by twisting the camera (so it has a sideways orientation or such), that is when you would modify "up."

# Answer
> 2 votes
Old question, but well. It appears that instead of:

```
glFrustumf(-size, size,
           -size / (rect.size.width / rect.size.height),
           size / (rect.size.width / rect.size.height), zNear, zFar);

```

You want the frustum to be slightly off, for instance by a quarter of the screen size:

```
glFrustumf(-size - size / 2, size - size / 2,
           -size / (rect.size.width / rect.size.height),
           size / (rect.size.width / rect.size.height), zNear, zFar);

```

# Answer
> 2 votes
I'm trying to do the same and found two ways of doing it:

One way is to render as if the screen is bigger, so that part of the viewport goes out of the screen and the viewport center align with the screen point you want (from a comment I can see that you've done this and it works), but it makes you draw more of the scene.

Another option (if you are using a version of OpenGL ES that supports vertex shaders) is to translate the resulting vertices (of the vertex shader, which should already be in projection space). This is something like:

```
gl_Position = u_model_view_proj_matrix * a_vertex_position;
gl_Position.xy = gl_Position.xy + u_viewcenter * gl_Position.w;

```

Where u\_viewcenter is a vec2 (from -1 to 1) that defines where you want the view center to be. This approach has some problems if you use the projection matrix in your code to do things such as picking or frustum clipping, since applying the projection matrix to the scene will no longer match the output of the vertex shader.

# Answer
> 0 votes
You should be able to apply a 2D offset/scale after the projection.

Just multiply the projection matrix by a suitable translation/scale matrix (where the translations are in the -1..1 range of viewport coordinates)

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


# Question
Title: Map editor undo function - Not actually setting values to tiles
I'm currently attempting to implement an undo/redo function for my map editor for a tile-based 2D platformer game made with XNA. I've found a lot of resources online about this and decided to try to write my own code for it to gain a better understanding of how it works.

My issue is when I pass the my tile's information into a stored "Action" and change the data within the newly created Action, it does not actually change the data in my tiles.

Below is the Action struct and the UndoBuffer class where I modify the tile's data based on the stored actions that I created elsewhere:

```
public struct Action
{
    public object[] StoredItem { get; set; }
    public object[] ModifiedItem { get; set; }
}

public class UndoBuffer
{
    private readonly List<Action> _undoBuffer;
    private readonly List<Action> _redoBuffer;

    public UndoBuffer()
    {
        _undoBuffer = new List<Action>();
        _redoBuffer = new List<Action>();
    }

    public void StoreAction(object[] storedItem, object[] modifiedItem)
    {
        var action = new Action {StoredItem = storedItem, ModifiedItem = modifiedItem};

        _undoBuffer.Insert(0, action);
    }

    public void Undo()
    {
        if (_undoBuffer.Count == 0) return;

        _redoBuffer.Insert(0, new Action {ModifiedItem = _undoBuffer[0].ModifiedItem, StoredItem = _undoBuffer[0].StoredItem});

        for (int i = 0; i < _undoBuffer[0].StoredItem.Count(); i++)
        {
            Action tempAction = _undoBuffer[0];
            tempAction.ModifiedItem[i] = tempAction.StoredItem[i];
            _undoBuffer[0] = tempAction;
        }

        _undoBuffer.RemoveAt(0);
    }
}

```

Here's how I'm passing the data in to the class above:

```
private void ReplaceTile(Tile oldTile, TileInfo tileInfo, bool storeAction = true)
{
    int tileX = (int)oldTile.Position.X / Tile.Width, tileY = (int)oldTile.Position.Y / Tile.Height;
    if (tileX < 0 || tileY < 0 || tileY >= _tileData.Tiles.Count || tileX >= _tileData.Tiles[tileY].Count) return;

    var storedTiles = new ArrayList();
    var modifiedTiles = new ArrayList();

    if (storeAction)
        storedTiles.Add(_tileData.Tiles[tileY][tileX].TileInfo);

    _tileData.Tiles[tileY][tileX].TileInfo = tileInfo;

    if (storeAction)
    {
        modifiedTiles.Add(_tileData.Tiles[tileY][tileX].TileInfo);
        _undoBuffer.StoreAction(storedTiles.ToArray(), modifiedTiles.ToArray());
    }

    _saved = false;
}

```

And here is the actual Tile class and its TileInfo struct:

```
public struct TileInfo
{
    public string ViewName;
    public int Frame;
    public TileCollision Collision;
    public CollisionType CollisionType;
    public TileProperty TileProperty;
    public SpriteEffects Effects;
    public Color TileColor;
    public float Rotation;
    public float Layer;
}

[Serializable]
public class Tile
{
    public TileInfo TileInfo;
    public Vector2 Position;

    public const int Width = 8;
    public const int Height = 8;

    public static readonly Vector2 Size = new Vector2(Width, Height);

    public Tile CreateTile(TileInfo tileInfo, Vector2 position)
    {
        var tile = new Tile
        {
            TileInfo = tileInfo,
            Position = position
        };

        return tile;
    }
}

```

So essentially, I just need the UndoBuffer class to actually change the data within the TileInfo structs that are passed into it, and not change a boxed copy of them.

# Answer
> 0 votes
I've figured out the issue, it was because I was editing copies of objects as I suspected, here are my code changes to solve the issue:

Undo code:

```
public void Undo()
{
    if (_undoBuffer.Count == 0) return;

    for (int i = 0; i < _undoBuffer[0].StoredItem.Count(); i++)
    {
        Type modifiedType = _undoBuffer[0].ModifiedItem[i].GetType();
        Type storedType = _undoBuffer[0].StoredItem[i].GetType();

        if (modifiedType != storedType) continue;

        foreach (var field in storedType.GetFields())
        {
            if (field.IsStatic) continue;
            var storedItemValue = field.GetValue(_undoBuffer[0].StoredItem[i]);
            var modifiedItemValue = field.GetValue(_undoBuffer[0].ModifiedItem[i]);

            field.SetValue(_undoBuffer[0].ModifiedItem[i], storedItemValue);
            field.SetValue(_undoBuffer[0].StoredItem[i], modifiedItemValue);
        }
    }

    _redoBuffer.Insert(0, new Action { ModifiedItem = _undoBuffer[0].ModifiedItem, StoredItem = _undoBuffer[0].StoredItem });
    _undoBuffer.RemoveAt(0);
}

```

Editor code:

```
private void ReplaceTile(Tile oldTile, TileInfo tileInfo, bool storeAction = true)
{
    int tileX = (int)oldTile.Position.X / Tile.Width, tileY = (int)oldTile.Position.Y / Tile.Height;
    if (tileX < 0 || tileY < 0 || tileY >= _tileData.Tiles.Count || tileX >= _tileData.Tiles[tileY].Count) return;

    var storedTiles = new ArrayList();
    var modifiedTiles = new ArrayList();

    if (storeAction)
        storedTiles.Add(_tileData.Tiles[tileY][tileX].Clone());

    _tileData.Tiles[tileY][tileX].TileInfo = tileInfo;

    if (storeAction)
    {
        modifiedTiles.Add(_tileData.Tiles[tileY][tileX]);
        _undoBuffer.StoreAction(storedTiles.ToArray(), modifiedTiles.ToArray());
    }

    _saved = false;
}

```

Instead of using the TileInfo struct which stored all of the data in each tile to pass into the undo function, I passed in the tiles themselves because they are of a reference type and not a value type. Within the undo class, instead of setting the ModifiedItem to the StoredItem directly (breaking the reference), I did a deep copy of the StoredItem's fields.

---
Tags: xna, software-engineering, tiles, data, map-editor
---


title: Block player movement

text:
# Question
Title: Block player movement
What do i need to keep my player model from going through environment objects like walls, trees etc?

Im trying to figure out if should use rigid bodies and the built in physics but i feel that its too difficult to predict what will happen then.

Is there an alternative that still will prevent the player from going through environment objects?

At the moment my player is a 3d model compsosed of some primitive shapes and a capsule collider.

# Answer
> 1 votes
Normally, physics simulation is done in three phases. First, in the so called broad phase, possible colliding bodies are determined. That is just to save computation time in the next step. Then, in the narrow phase, actually collisions and constraints are detected. Afterwards, they get resolved.

Implementing such a physics simulation is a big effort, which I don't advice you to take yourself. Since you used the `unity` tag, you may use the physics simulation integrated in that engine. Otherwise, there is a very popular open library called Bullet Physics.

If you want to implement something yourself, especially for learning purpose, you can drastically simplify things for now. For example, don't calculate triangle accurate collisions for your bodies, but just check their bounding boxes. Those can be constructed by their minimum and maximum coordinates in all directions. Or instead, you might want to treat every body as a sphere in the physics simulation, only represented by a radius.

---
Tags: unity, physics
---


# Question
Title: How to move an object up and down like a wave?
I am trying to move my object up and down using `cos` and `sin`, but I have problem understanding how does the `sin` and `cos` work, so I can make my object move up and down like a wave frequently

Init Time starts from value of 16.00 it keeps on increment up to 17.065

```
initTime += msec * 0.001;
float x  =  cos(initTime* 2.46) * 2075;
float y  =  sin (initTime* 2.888) * 200;

```

My object goes down and up, then goes back to its initial position, then goes up and down once again, I want it to be like a wave

# Answer
> 10 votes
I still think you need to understand basic trigonometry. But here is a simple introduction of how to use `sin` and `cos` to simulate a wave.

The basic wave formula is:

> f(t) = *A* * sin( 2 * pi * *f* * *t* \+ *phase* )

Where:

> * ***f*** is the **frequency**, which controls the number of times the waves repeats per unit time, *f* = 1/*P* where *P* is the number of periods.
> * ***A*** is the **amplitude** of the wave, which represents the highest and lowest points of the wave.
> * **2\*pi** is a **scaling factor** to be able to deal with the equation in terms of frequency and periods. (in other words, make it easier and more intuitive).
> * ***t*** is a parameter that represents time, or any other varying quantity.

The relation between a `cos` and a `sin` wave is only `pi/2` phase shift.

> cos(t) = sin(t + pi/2 );

What you only need to do to make your object move, is to vary `t` over time, inject it into the wave equation, and multiply your object possibly the `Y` position with the computed result from the wave equation.

Implementing this is straightforward

```
float initx = 0;
float inity = 0;
Object.x = initx+ time;
Object.y = inity+ (a * sin(2 * PI * f * t + phase));

```

But keep in mind that this will *not* simulate how an object would float on water. The topic would be much more complicated. This will only simulate a sine wave.

---
Tags: mathematics, matrix
---


# Question
Title: Making player movement direction follow players facing direction
```
if (controller.isGrounded) {
                        moveDirection = new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical"));
                        moveDirection = transform.TransformDirection (moveDirection);
                        moveDirection *= speed;
                        if (Input.GetButton ("Jump"))
                                moveDirection.y = jumpSpeed;

                }
                moveDirection.y -= gravity * Time.deltaTime;
                controller.Move (moveDirection * Time.deltaTime);

```

This works. I can manover my player in any direction.

With the awsd keys i can create 8 directions. I would like player to rotate towards the direction of the keys pressed. This is a top down game. So W+D would take you diagonally right/up. S+D would take you diagonally right/down.

I want the player to rotate into that direction, but also move the direction it is facing. Like a car. So if it is facing a complete different direction then it would actually move not in the target direction for a while until it has the target direction. Am i making sense?

```
      if (moveDirection != Vector3.zero)
    {
transform.rotation = Quaternion.LookRotation (moveDirection);
                        }

```

# Answer
Don't move the player's position directly in response to keyboard input. Instead always move the player forward relative to the direction it's facing, and lerp to different rotations based on keyboard input.
> 2 votes

---
Tags: unity, physics, rotation, movement, quaternion
---


title: Game economy for a tower defense game

text:
# Question
Title: Game economy for a tower defense game
I am currently working on a tower defense game, and I am having trouble figuring out how to implement the cost of turrets, upgrades, and the gain from completing a level, killing an enemy. Below is a summary of the requirements:

> * There are multiple types of turrets, each turret has different properties, such as reload speed, range. Each upgrade has multiple levels.
> * Each turret can have multiple types of ammo, each ammo type can have different upgrades, such as blast range, damage, addons. Each upgrade has multiple levels
> * The sources of income are
>     + killing enemies, each enemy has a different value
>     + completing a level

My problem is with balancing everything so the game is at least playable, or in the right direction to get balanced by testing it. I know there is no magic formula for this but I believe people with experience will know where to start, and what process to follow. So my questions are:

1- is there a method to calculate the cost of turrets, upgrades? what factors should I take into consideration? 2- Should I use two different currencies for upgrades and turret purchases? 3- How to calculate the upgrade cost as the upgrade level increases? i.e. when the user purchases more of the same upgrade.

# Answer
Excel is your friend. Calculate the cash earned by level, and think of how many levels before a player "should" be able to buy something -- there's the cost right there.

Here's a simple example. Imagine, for simplicity's sake, two turrets with two ammo types each.

* Turret 1: slow/ranged. Ammo is artillery shells and grenades.
* Turret 2: fast/close. Ammo is bullets and lasers.

You want T2/Bullets in level 2, T1/shells in level 3, T2/lasers in level 6, and T2/grenades in level 10.

Further assume you get `N * 100` gold for completing level `N` (eg. 100, 200. ...). In this case, it's easy to calculate the following costs:

* T2/Bullets: 300 (100 + 200)
* T1/Shells: 600 (100 + 200 + 300)
* T2/Lasers: 2100 (100 + 200 + ... + 600)
* T2/Grenades: 5500

Tweak your formulas and parameters accordingly until it seems right. Then playtest it and see if it feels right.
> 3 votes

# Answer
Extending the comment made by @ashes999: Make a big Excel spreadsheet, then calculate every metric you can get. This includes:

* How much cash gain per level (starting gold, gold per monster)
* How many Enemies can each update / ammo combination take out in a single wave
* Based on above Information: Which tower combination is viable for this level
* How much would each of this combination cost

With this you could do a lot of stuff:

* Calculate the maximun and minimum amount of gold needed to win this level.
* Decide how much gold you want to provide (maybe based on difficulty setting)
* Adjust starting gold and gold per enemy

Hope this gets you started!
> 2 votes

---
Tags: game-design
---


# Question
Title: Android OpenGL ES 2 framebuffer not working properly
I'm trying to understand how framebuffers work. In order to achieve that, I want to draw a very basic triangle to a framebuffer texture and then draw the resulting texture to a quad on the default framebuffer.

However, I only get a fraction of the triangle like below. LE: The triangle's coordinates should be `(1) -0.5f, -0.5f, 0 (2) 0.5f, -0.5f, 0 (3) 0, 0.5f, 0`

Here's the code to render:

```
@Override
public void onDrawFrame(GL10 gl) {
    renderNormalStuff();
    renderFramebufferTexture();
}

protected void renderNormalStuff() {
    GLES20.glViewport(0, 0, texWidth, texHeight);
    GLUtils.updateProjectionMatrix(mProjectionMatrix, texWidth, texHeight);

    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fbo[0]);

    GLES20.glUseProgram(mProgram);

    GLES20.glClearColor(.5f, .5f, .5f, 1);
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);

    Matrix.setIdentityM(mModelMatrix, 0);
    Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);
    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);

    GLES20.glUniformMatrix4fv(u_MVPMatrix, 1, false, mMVPMatrix, 0);

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vbo[0]);
    GLES20.glVertexAttribPointer(a_Position, 3, GLES20.GL_FLOAT, false, 12, 0);

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vbo[1]);
    GLES20.glVertexAttribPointer(a_Color, 4, GLES20.GL_FLOAT, false, 16, 0);

    GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, ibo[0]);
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, indexBuffer.capacity(), GLES20.GL_UNSIGNED_BYTE, 0);

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
    GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);

    GLES20.glUseProgram(0);
}

private void renderFramebufferTexture() {
    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);

    GLES20.glUseProgram(fboProgram);

    GLES20.glClearColor(.0f, .5f, .25f, 1);
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

    GLES20.glViewport(0, 0, width, height);

    GLUtils.updateProjectionMatrix(mProjectionMatrix, width, height);

    Matrix.setIdentityM(mModelMatrix, 0);
    Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);
    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);

    GLES20.glUniformMatrix4fv(fbo_u_MVPMatrix, 1, false, mMVPMatrix, 0);

    //draw the texture
    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[0]);
    GLES20.glUniform1i(fbo_u_Texture, 0);

    GLUtils.sendBufferData(fbo_a_Position, 3, quadPositionBuffer);
    GLUtils.sendBufferData(fbo_a_TexCoordinate, 2, quadTexCoordinate);

    GLES20.glDrawElements(GLES20.GL_TRIANGLES, quadIndexBuffer.capacity(), GLES20.GL_UNSIGNED_BYTE, quadIndexBuffer);

    GLES20.glUseProgram(0);
}

```

# Answer
Sorted it out eventually. The code above is correct, yet my `quadPositionBuffer` used incorrect coordinates.
> 0 votes

---
Tags: opengl-es2
---


title: 3rd person game with rigid body

text:
# Question
Title: 3rd person game with rigid body
Im making a 3rd person 3D game. I have a little capsule shaped player controlled drone at the moment that moves on a flat surface. Y axis is locked. The Game object contains a script and then the child objects which are the actual body parts. If i attach a rigidbidy to the root object i get crazy results. The drone collides with something and starts to spin and then forward becomes some upward direction.

Somehow i would like to be able to use the pysics collision and ragdoll effects but still be able to maintain the keyboard movement. I guess that id have to animate the drone getting back up again when fallen.

Movement code

```
    void CheckForKeys ()
{
    if (Input.GetKey(KeyCode.W)) {
        transform.Translate(Vector3.forward * Time.deltaTime * walkingSpeed);
    }

    if (Input.GetKey(KeyCode.S)) {
        transform.Translate(Vector3.back * Time.deltaTime * walkingSpeed);
    }

    if (Input.GetKey(KeyCode.A)) {
        transform.Rotate(Vector3.up * Time.deltaTime * rotatingSpeed);
    }

    if (Input.GetKey(KeyCode.D)) {
        transform.Rotate(Vector3.down * Time.deltaTime * rotatingSpeed);

```

# Answer
If the root and child colliders intersect from the beginning the physics can present weird behaviour.
> 0 votes

---
Tags: unity, rigid-body-dynamics
---


title: How can an anticheat pass WACK test?

text:
# Question
Title: How can an anticheat pass WACK test?
On of the rules for app validation for the Windows Store is:

> **3.9 All app logic must originate from, and reside in, your app package**
>
> Your app must not attempt to change or extend the packaged content through any form of dynamic inclusion of code or data that changes how the application interacts with the Windows Runtime, or behaves with regard to Store policy. **It is not permissible, for example, to download a remote script and subsequently execute that script in the local context of your app package**.

*\[emphasis added on last sentence\]*

AFAIK many anti-cheat softwares work by downloading and executing an executable file every 30 seconds or so, and reporting back the result. This obviously cannot be accomplished if you aren't able to continually download it yourself and execute it.

So, is there something different which works on Windows Store and is good enough, or will Windows Store games just lack anti-cheat features for now?

# Answer
> 1 votes
You could just add the anti-cheat tool to your store package and rely on the stores update-mechanism for keeping the anti-cheat component up-to-date.

Before you wonder if this might undermine the security of the ACT and might make it possible to manipulate it, keep in mind that ACT's can't be effectively protected from manipulation anyway. Never trust the client!

---
Tags: anti-cheat, windows-8
---


title: Swaying tree in OpenGL ES 2

text:
# Question
Title: Swaying tree in OpenGL ES 2
I've seen this many times, but I have no idea what's the best way to achieve it. I am looking for something close to, for example, this: Lonely Tree Live Wallpaper

I have two approaches in mind: one would be to make an animation in, say, Blender and then export the resulting images & create a spritesheet animation out of it. This is very straightforward, but creating a 120-frame spritesheet out of 512 x 512 or 1024 x 1024 images (for larger screens) seems overkill.

The second approach would be to cut my tree into a few separate textures and then move them simultaneously in such a manner that it gives the impression they form a single image of a tree swaying in the wind.

Any other approaches?

# Answer
Maybe use skinning? Create a mesh in blender, make an armature for it. Assign each vertex weights to different bones in the armature.

When you're rendering the tree, send in one matrix (or quaternion) for every bone in the trees armature. In the vertex shader, lookup the current vertex's weights for the provided matrixes, and transform it accordingly.

Eg

```
#define numberOfBones 24
in vec3 vertex;
in vec3 weights;
in vec3 bones;

uniform mat4[numberOfBones] matrixes;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main() {

  Matrix compositeMatrix = (matrixes[bones.x] * weights.x) * (matrixes[bones.y] * weights.y) * (matrixes[bones.z] * weights.z);
  glPosition = projectionMatrix * viewMatrix * compositeMatrix * vec4(vertex, 1);
}

```

Note that this example would only allow a vertex to be influenced by 3 different bones, but due to the limitations of GLSL in OpenGL ES 2.0 this will do.

Maybe you would not need to create an animation for it, maybe you could do it procedurally. You could start off with the bone closets to the ground, and represent wind sway through it's matrix by an rotation with some strength (eg, if the wind blows dead on along the x axis, rotate the matrix along the z axis). Then for the next bone(s) immediately connected to that bone, take the matrix you just calculated and rotate it further. Don't forget that the strength of the wind sway need to vary, sin or cos is good for this, but maybe you'd like and more logarithmic type vary.

```
void uploadBoneMatrix(Node node, float parentStrength, Matrix parentMatrix, Vector displacement) {
    Matrix nodeMatrix = parentMatrix.copy(); //deep copy
    nodeMatrix.translate(displacement);
    float strength = parentStrength + Math.sin(some fucking intervall);

    Matrix additionalRotation = new Matrix().rotateAroundZAxis(strength);
    nodeMatrix = nodeMatrix * additionalRotation; //don't forget that matrix multiplication is not commutative

    GLES20.glUniform4fv(shader.getBoneIndex(node.boneIndex), nodeMatrix);

    for every Node child of node {
        Vector displacement = node.endPoint.copy()/* deep copy */ * nodeMatrix ;
        uploadBoneMatrix(child, strength, nodeMatrix.copy() /* deep copy */, displacement );
    }

}

```

And call uploadBoneMatrix on the root node.

I think that could look really cool.

Edit:

Also, out of your two approaches I liked the second one best. Maybe it would look a bit rigid, but I'm sure you could make it entirely believable.

Edit2:

I assume that you're using Android or something, GLES20 is just any arbitrary handle to an OpenGL context. Also, naturally you do uploadBoneMatrix before you render the tree.

Edit3:

I realized that you also must displace every child
> 1 votes

---
Tags: opengl-es2
---


# Question
Title: Is there a way to create a sky-sphere instead of a skybox in Unity3D?
In a 3D game, how can I make a sky background seen at the horizon? I tried adding a texture to the skybox but since it's a box it looks horrible.

When I'm not using a texture it's not notable that it is actually a box so it looks better.

I can imagine doing the same with a huge sphere but I imagine there is a proper way of doing it, so I thought I would ask.

# Answer
First, make sure you're not applying lighting to the skybox. It should be full brightness without any lights. Lights make box edges visible even without textures, so you're probably not doing that.

Second, your choice of texture needs to be seamless and well chosen as a skybox texture(s). If you're rendering a literal sky *box* then the textures need to also be created with knowledge that they're mapped to a box and be distorted in such a way that it appears non-boxy near the seams, essentially the same as a cubemap.

There are more advanced ways of rendering skyboxes which give even better results, but that's the gist of the basic version. Here's a fixed-function OpenGL tutorial that will maybe explain things better than I did.
> 2 votes

---
Tags: 3d, unity, skybox
---


title: SDL 2.0 filtering mouse events

text:
# Question
Title: SDL 2.0 filtering mouse events
I have a simple 2-D breakout clone. It works fine, except for one bug.

If I move mouse over game window, it will get input from mouse(mouse movement), and event queue will instantly be flooded with this input. For example, if player pressed left arrow, but moved his mouse over a window before, he will have to wait enough frames for mouse events to get processed. Is there a way to ignore mouse event? At least these movement ones. Everything is okay when mouse doesn't move, but after it moves it's terrible.

I'm using SDL 2.0, programming on Debian-based linux. Using C++.

Code for handling events looks like this(requested):

```
void gameEngine::HandleEvents()
{
    if( SDL_PollEvent(&gameEvent) != 0 )
    {
        HandleEngineEvents();
        gameLevel.HandleEvents(gameEvent);
    }
}

```

HandleEngineEvents() :

```
void gameEngine::HandleEngineEvents()
{
    if( gameEvent.type == SDL_QUIT)
    {
        running = false;
    }
    else if( gameEvent.type == SDL_KEYDOWN && gameEvent.key.repeat == 0 )
    {
        if( gameEvent.key.keysym.sym == SDLK_ESCAPE )
        {
            running = false;
        }
    }
}

```

Level::HandleEvents() :

```
void Level::HandleEvents(SDL_Event& gameEvent)
{
    player.HandleEvents(gameEvent);
}

```

Player::HandleEvents() :

```
void Player::HandleEvents(SDL_Event& gameEvent)
{
    if(gameEvent.type == SDL_KEYDOWN && gameEvent.key.repeat == 0)
    {
        switch(gameEvent.key.keysym.sym)
        {
        case SDLK_RIGHT:
             velocity += 1;
            break;
        case SDLK_LEFT:
            velocity -= 1;
            break;
        default:
            break;
        }
    }
    else if(gameEvent.type == SDL_KEYUP && gameEvent.key.repeat == 0)
    {
        switch(gameEvent.key.keysym.sym)
        {
        case SDLK_RIGHT:
             velocity -= 1;
            break;
        case SDLK_LEFT:
            velocity += 1;
            break;
        default:
            break;
        }
    }
}

```

# Answer
The documentation says about `SDL_PollEvent`:

> Use this function to poll for currently pending events.

And you are supposed to use it this way (still from the doc):

```
while (1) {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
         // handle your event here
    }
    // do some other stuff here -- draw your app, etc.
}

```

In fact, you can have several events occurring between frames and the way you are doing it, you will only handle one event per frame because you call the function once. To proceed all the events in the queue, you have to loop on `SDL_PollEvent` returns 0 (no more event in the queue).

So just to explain a bit more, if you have 15 mouse dragging events from the frame N, with your code, you will handle one of them. Then, in the frame N+1, you could have a mouse click event, it will be added to the queue after the 14 remaining dragging events. So you would need to wait N+14 to see your click event handled.

So i would say, replace your `if` statement by a `while` statement.

EDIT: it doesn't really answer your question since i don't tell you how to filter events but it's not the cause of your problem.
> 7 votes

# Answer
You can use the SDL function SDL\_SetEventFilter as detailed here:

http://www.libsdl.org/release/SDL-1.2.15/docs/html/sdlseteventfilter.html

Basically, it takes as a parameter a function to use as a filter which events will be passed through and then determined as valid or invalid. The function should return 1 if valid or 0 if invalid.

For example, you may define a filter function:

```
int isMouseEvent(const SDL_Event* event)
{
    if (event->type == SDL_MOUSEMOTION)
        return 0;
    return 1;
}

```

Then somewhere else in the program set up the SDL\_SetEventFilter:

```
// code bla bla
SDL_SetEventFilter(isMouseEvent);

```

I hope this was clear. It solved the exact same problem for me.

EDIT: I just noticed that you are using a different version of SDL, so the answer may be slightly different in your case. According to http://www.ginkgobitter.org/sdl/?SDL\_SetEventFilter you may need to specify an extra parameter in your filter function but it seems the basic logic is exactly the same.
> 5 votes

---
Tags: c++, sdl
---


# Question
Title: "Walking" along a rotating surface in LimeJS
I'm trying to have a character walk along a plank (a long, thin rectangle) that works like a seesaw, being rotated around a central point by box2d physics (falling objects). I want the left and right arrow keys to move the player up and down the plank, regardless of it's slope, and I don't want to use real physics for the player movement.

My idea for achieving this was to compute the coordinate based on the rotation of the plank and the current location "up" or "down" the board.

My math is derived from here: https://math.stackexchange.com/questions/143932/calculate-point-given-x-y-angle-and-distance

Here's the code I have so far:

```
movement = 0;
if(keys[37]){ // Left
    movement = -3;
}

if(keys[39]){ // Right
    movement = 3;
}

// this.plank is a LimeJS sprite.
// getRotation() Should return an angle in degrees
var rotation = this.plank.getRotation();

// this.current_plank_location is initialized as 0
this.current_plank_location += movement;

var x_difference = this.current_plank_location * Math.cos(rotation);
var y_difference = this.current_plank_location * Math.sin(rotation);

this.setPosition(seesaw.PLANK_CENTER_X + x_difference, seesaw.PLANK_CENTER_Y + y_difference);

```

This code causes the player to swing around in a circle when they are out of the center of the plank given a slight change in rotation of the plank.

Any ideas on how I can get the player position to follow the board position?

# Answer
One issue is that Math.cos/Math.sin take radians, not degrees. E.g.,

```
> Math.cos(Math.PI)
-1
> Math.cos(180)
-0.5984600690578581

```

So, you're going to have to convert the rotation:

```
rotation = rotation * (Math.PI/180);

```
> 2 votes

---
Tags: movement, geometry, trigonometry
---


# Question
Title: how do I modify Texture2DArray values in shader
I'm using HLSL Shader Model 5.0. I'm using a Texture2D with the vertex positions for a mesh. In the Shader I'm trying to displace patchepositions along the normal of the patches I'd like to actualize the new position to the texture out of the shader, so the next patch is using the modified value. There is the Load function for loading values out of the texture, but is there a function to store values back into the texture? I didn't find anything. How do you guys managing similar problems? thx

# Answer
In Direct3D 11.1 you can use unordered access views (UAVs) for read-writable textures in all shader stages. So you can add an `RWTexture2D` to your vertex shader and use it to store values as the vertices are shaded. However, this functionality isn't available in Direct3D 11.0 or earlier, and 11.1 is only available on Windows 8.0 or higher.

If you're limited to Direct3D 11.0, you could implement your displacement operation using a pixel shader and doing a standard full-screen pass on the texture containing the positions. Another possibility (though likely slower) is using a compute shader. In either case, you would do this as a pre-pass before actually drawing the displaced mesh.
> 1 votes

# Answer
You cannot moddify textures in the pixelshader that way, the only way to do that is to render to a texture.

Direct compute offers you the possibility to read and write data to a texture on demand. you could achive your diserd effect by having a Direct compute pass.

Here is a good link to msdn about compute shaders
> 0 votes

# Answer
Since it's vertex data you want to store somewhere you also have the option of using stream out from either the vertex or geometry shader.
> 0 votes

---
Tags: shaders, hlsl, directx11
---


# Question
Title: Is it possible to gain performance by omitting vertex normals in the GPU pipe?
I am working on a rendering problem where I want to render as many raw triangles to the screen as I can with either OpenGL or DirectX with the absolute fastest performance possible.

I wondered about omitting vertex normals completely and only transforming vertex positions during the vertex shader stage.

1) Is this possible?

2) Is it actually going to increase performance --or-- is the "bare metal" of the GPU designed in such a way that trying to omit normals won't gain any more throughput?

p.s. Yes, I realize that omitting normals will leave you with the problem of how to shade the triangle during the shader stage, but I could at least render a solid color to the screen (no shading). *At this point, all I'm wondering about is how much data I can eliminate from the typical pipeline to increase the pipeline throughput to the absolute maximum.*

# Answer
Yes, it is possible. When you configure your input layout (in D3D10+) or vertex attributes (OpenGL), simply only include the position. Don't configure any additional data such as normal or texture coordinates.

Then, when you fill your vertex buffers, you only need to fill them with position data. Perform your fixed coloring in the fragment shader.

This will be slightly faster, because your vertex shader doesn't need to transform or handle the extra data at all. You also won't need to copy as much data from the CPU to the GPU when you define the buffers. Will it be appreciably faster? I'd guess no, but if you're pushing as much data as possible, then maybe. You'd have to profile it and see.
> 4 votes

# Answer
You're unlikely to be bus-limited or vertex-limited on current or even recent hardware; except in extreme and unlikely scenarios, fillrate and ROP will kick in a lot sooner.

If omitting normals gets your vertex size below 32 bytes that can be a win. If you still need some kind of shading, you can get normals down to 4 bytes (instead of 3 floats) by using a signed/normalized vertex format, and it will look sort of OK.

But if drawing the maximum number of triangles possible is your goal, you'll get much more mileage from batching draw calls, and shifting CPU-side calculations to the GPU (even if it means doing some of them per-vertex rather than per-triangle, i.e. a 3x increase) so as to allow you to keep your vertex data in static buffer objects.
> 2 votes

# Answer
The performance difference will depend a lot on the hardware you're using, the only way to be sure is to test it.

Technically you don't need a vertex buffer or index buffer at all - you can generate the position in the vertex shader in DX10/11, based on the integer index of the vertex.

You can of course also skip the transform, by passing coordinates through in clip space.
> 2 votes

---
Tags: opengl, directx, performance, vertex, normals
---


# Question
Title: XNA soundEffect is null in when loaded in main class and called in another class
I have loaded a sound effect file into the main class in xna, but when I try to run it in another class I am given this error

> {"Object reference not set to an instance of an object."}

I am new to XNA classes so I do not really understand them. Any help as soon as possible is greatly appreciated.

this is part of the main class

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace BreakingOut
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Ball ball;
    Paddle paddle;
    Rectangle screenRectangle;
    bool is1P = true;

    int lives = 3;

    Texture2D startButtonTexture;
    Vector2 buttonVec;

    Texture2D exitButtonTexture;
    Vector2 button2Vec;

    int bricksWide = 10;
    int bricksHigh = 7;
    Texture2D brickImage;
    Brick[,] bricks;

    //rec for menu
    Texture2D menuTexture;
    Rectangle menuRec = new Rectangle(0, 0, 960, 640);
    //rec for pause
    Texture2D pauseTexture;
    Rectangle pauseRec = new Rectangle(0, 0, 960, 640);
    //lose
    Texture2D loseTexture;
    Rectangle loseRec = new Rectangle(0, 0, 960, 640);

    Texture2D winTexture;
    Rectangle winRec = new Rectangle(0, 0, 960, 640);

    //sound effects
    public  SoundEffect BallHitSE;
    SoundEffect WallHitSE;
    SoundEffect StartSE;
    //BGM
    Song menuMusic;
    Song gameMusic;

    bool isGameMusicPlaying = false;
    bool isMenuMusicPlaying = false;

    float pauseTimer;
    float exitTimer;
    float muteTimer;
    float SEmuteTimer;

    //public int brickCount = 70;

    SpriteFont font;

    Vector2 mousePos;

    enum gameStates
    {
        MENU,
        GAME1P,
        LOSE,
        PAUSE,
        WIN,
    }

    gameStates currentState = gameStates.MENU;
    gameStates prevState = gameStates.MENU;

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

        IsMouseVisible = true;

        graphics.PreferredBackBufferWidth = 960;
        graphics.PreferredBackBufferHeight = 640;

        screenRectangle = new Rectangle(
            0,
            0,
            graphics.PreferredBackBufferWidth,
            graphics.PreferredBackBufferHeight);
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        Texture2D tempTexture = Content.Load<Texture2D>("paddle");
        paddle = new Paddle(tempTexture, screenRectangle);

        BallHitSE = Content.Load<SoundEffect>("BallHit");
        WallHitSE = Content.Load<SoundEffect>("WallHit2");
        StartSE = Content.Load<SoundEffect>("Start");
        gameMusic = Content.Load<Song>("gameMusic");
        menuMusic = Content.Load<Song>("menuMusic");

```

This is the Ball class

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace BreakingOut
{
class Ball
{
    Vector2 motion;
    Vector2 position;
    Rectangle bounds;
    bool collided;

    public int brickCount = 70;

    const float ballStartSpeed = 6.4f;
    public float ballSpeed;

    Texture2D texture;
    Rectangle screenBounds;

    SoundEffect BallHitSE;
    //BallHitSE = new SoundEffect

    public Rectangle Bounds
    {
        get
        {
            bounds.X = (int)position.X;
            bounds.Y = (int)position.Y;
            return bounds;
        }
    }

    public Ball(Texture2D texture, Rectangle screenBounds)
    {
        bounds = new Rectangle(0, 0, texture.Width, texture.Height);
        this.texture = texture;
        this.screenBounds = screenBounds;
        //Different things we tried
        //BallHitSE = Content.Load<SoundEffect>("BallHit");
        //BallHitSE =  new soundeffect(what goes in here?);
        //BallHitSE = Content.Manager.Load("path")

    }

    public void Update()
    {
        collided = false;
        position += motion * ballSpeed;
        ballSpeed += 0.001f;

        CheckWallCollision();
    }

    public void CheckWallCollision()
    {
        if (position.X < 0)
        {
            position.X = 0;
            motion.X *= -1;
            //if (BallHitSE != null)
            //{
                BallHitSE.Play();
            //}
        }
        if (position.X + texture.Width > screenBounds.Width)
        {
            position.X = screenBounds.Width - texture.Width;
            motion.X *= -1;
            //if (BallHitSE != null)
            //{
                BallHitSE.Play();
            //}
        }
        if (position.Y < 0)
        {
            position.Y = 0;
            motion.Y *= -1;
            //if (BallHitSE != null)
            //{
                BallHitSE.Play();
            //}
        }
    }

    public void SetInStartPosition(Rectangle paddleLocation)
    {
        Random rand = new Random();

        motion = new Vector2(rand.Next(2, 6), -rand.Next(2, 6));
        motion.Normalize();

        ballSpeed = ballStartSpeed;

        position.Y = paddleLocation.Y - texture.Height;
        position.X = paddleLocation.X + (paddleLocation.Width - texture.Width) / 2;
    }

    public bool OffBottom()
    {
        if (position.Y > screenBounds.Height)
            return true;
        return false;
    }

    public void PaddleCollision(Rectangle paddleLocation)
    {
        Rectangle ballLocation = new Rectangle(
            (int)position.X,
            (int)position.Y,
            texture.Width,
            texture.Height);

        if (paddleLocation.Intersects(ballLocation))
        {
            position.Y = paddleLocation.Y - texture.Height;
            motion.Y *= -1;
        }
    }

    public void Deflection(Brick brick)
    {
        if (!collided)
        {
            motion.Y *= -1;
            collided = true;
            brickCount -= 1;
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, position, Color.White);
        for (int i = 1; i < 10; i++)
        {
            var drawPosition = position - (i * motion * 3);
            var colour = Color.Lerp(Color.White, Color.Transparent, i * (20 / 100f));
            spriteBatch.Draw(texture, drawPosition, colour);
        }
    }
}
}

```

# Answer
> 0 votes
Make sure, Ball is instantiated before LoadContent().

Then swap this line

```
BallHitSE = Content.Load<SoundEffect>("BallHit");

```

with this

```
Ball.BallHitSE = Content.Load<SoundEffect>("BallHit");

```

and change the variable in your Ball class to this

```
public SoundEffect BallHitSE;

```

---
Tags: xna, c#, sound-effects
---


# Question
Title: HLSL postprocessing for day to night (DTN)
I am trying to implement a "day-to-night"-filter (as commonly used in cinema) for a 2D game (XNA) by using a full screen HLSL pixel shader. The aim is to transform any bright and colorful image into a dark and bluish night version of that image somewhat like:

Conceptually, my ideas would be to:

* Decrease brightness
* Merge blueish tinted greyscale version of image with original image
* Increase contrast

The current shader I came up with is:

```
// Look up the color of the original pixel
float3 colorOriginal = tex2D(TextureSampler, texCoord);

// Get corresponding greyscale value (adjusted to human vision)
float greyscale = dot(colorOriginal, float3(0.3, 0.59, 0.11));

// Merge and tint
color.rgb = lerp(colorOriginal, colorOriginal * float3(pow(greyscale,6), pow(greyscale,6), pow(greyscale,3)), timeFactor);

```

The result is still not completely satisfying. How could I improve this?

# Answer
Basicly, postprocessing might be a bad way of doing "night time". "Night time" consist of alot of diffrent aspects floating into one bigger picture.

To get similar results to what happens in the image here is not a simple task. The light and shadows play a big part of this, aswell as the moonlight that they have.

What you could achive with post processing here is more of a tonemapping and filmic grain. Now i dont know your limitations and so on, so itś easy just to say that "this wont work". But elaborating your answer a bit around how your current game looks ( an image for instance would be of greate help )

But for your Grayish color tone, you have to narrow down the range betweeen the colors, so that you store 255 colors in a range from 0.2-\>0.4. from there you can adjust the brightness to what ever you want by simply adding a constant value.

For bluring, you probably want to do some sort of "Range", where you add blur to the image. otherwise the image will lose itś estethics. So say that you do an avrage check of the 4 adjesent pixels and if the range is in the topp then you can blur that pixel.
> 3 votes

---
Tags: xna, shaders, graphics, hlsl, post-processing
---


# Question
Title: How to show the bow string stretching animation (?)
I was wondering how the animation in the angry birds of pulling the slingshot is done. One similar animation is available in this game but with a bow and arrow. I think both of them use the almost similar technique for it.

I tried to search for this on Google and all I got was the trajectory related stuff like calculating the trajectory of object once it is thrown. I could not find anything related to how the animation (?) for stretching the slingshot/bow string with respect to the force applied by user the bow string is achieved.

Can anybody point me in right direction in how to achieve that effect. Tutorials are welcome!

# Answer
it's as simple as drawing a line from the anchor to the object after you calculate the location of it,

you can also make the string thinner as it gets stretched to imitate a rubber band stretching
> 2 votes

---
Tags: animation, physics
---


# Question
Title: How to make different layers in a 2d game map
My question is this: How do I make a gamemap from the drawings on my spritesheet?

The tutorial I have followed for making a java 2D game uses this technique to make a gamemap: in photoshop I create a new document with each pixel representing a tile in the game map. Each tile is assigned a unique hexadecimal color value and from there it is a breeze to load the .png file into the game.

However, now that I have a complete map filled with all the basic tiles, it's still a very empty map. I want trees, bushes, flowers on my grass tiles. seaweed, water lilies, driftswood and whatnot on my water tiles. All sorts of scenary that is simply a must to make a simple game map. Many of these "scenery" objects I intend to design bigger than 1 tile (structures, for example). And not necessarily entire tiles either (some will have transparent parts). I'm at a complete loss and don't even know what to expect for an answer.

Am I supposed to draw a tree (with a mass of 8 tiles) as 8 seperate tiles? Am i supposed to draw even larger objects (20x20 warehouses) on top of basic tiles? What I really hope to learn is how the gamemaps have been made in the Pokemon games for gameboy, for instance.

My current thoughts are to design a new class in my projects resembling the Tile class, this one Scenary. Like Tile it will contain an array of every single scenary object in the game, each with a unique color code to be represented as a pixel in a .png document. The pixel representing the start-point of the scenary and the individual scenary object should contain information about how to render from its start position.

If not entirely ridiculous this method can't possibly the right way to go. The Scenary class could, unlike the Tile class, have potentially hundreds of objects in its array.

# Answer
> 2 votes
Using a bitmap as map format where one pixel is one tile might be a quick hack to substitute a proper map editor, but when your maps become more complex (multiple layers, objects, zones, map properties etc.), you will soon feel the need for a proper WYSIWYG editor. You could either develop such an editor yourself which reuses your graphic engine and exports into your own map format, or you could use an existing editor and adopt its map format. Unless you have some really exotic requirements for map editing I would recommend you to do the latter - it will save you lots of time. I can recommend Tiled.

Large objects like warehouses are usually made of modular tiles which fit together in different ways. Here is a town tileset I made for the open source game The Mana World and here is a screenshot of it in action. As you can see the building tiles can be combined in different ways to form large or small buildings.

When we developed The Mana World, our graphic engine used three layers:

* Ground (drawn before drawing the sprites)
* Fringe (drawn together with the sprites in order of y-coordinate)
* Over (drawn after the sprites)

A 3x2 tile tree consisted of 6 tiles, two on each layer, to make sure they overlap the players properly when they stand in front or behind them. Later we added support for "oversized tiles" on the fringe layer: Tiles with the normal width but several tiles high. This was mostly for the convenience of our mappers, because they could now place a tree with two clicks on one layer instead of six clicks on three. This improved productivity and greatly reduced the amount of mapping errors. As a side-effect we barely use the over-layer anymore because most map designs can be done using only ground and fringe with oversized tiles.

# Answer
> 0 votes
from what i can figure from your question here are two possible answers

* a) draw your objects into a similar tile sheet and assign color values to them. then save them into a new map and just load maps on top of each other. The flaw here of course is that you will have to count individually where each tile'pixel' goes--unless you code your self a simple map editing tool, then you can make the map as one layer by layer and save it as individual layers or even a conglomerate of layers(aka one huge image).
* b) create your objects separately in their natural format and save their coordinates in your world in a different format. then easily load them up with your map and render them appropriately

Although once your maps start becoming more complex you will face scalability issues. Where you will need to go back and refactor what you have been working with for so long(which sometimes can take more time than if you would have gone with a more flexible solution from the start).

---
Tags: java, 2d, tilemap, spritesheet
---


# Question
Title: Unity3D JavaScript/.NET code throwing compilation error with a List-thingy
So, I do this:

```
var intlist:List.<System.Int32>;
intlist.Add(1);

```

And where I say intlist.Add(1) I get:

```
NullReferenceException: Object reference not set to an instance of an object

```

Weird, huh? Apparently, the error is .NET related and List is a .NET thing. So, please clarify the problem. Thank you.

EDIT:

The "add comment" button isn't working, so I will respond in the form of an edit. No, I can't use a JavaScript array because for whatever reason it screws up in the context of my code and the Unity people say I shouldn't use them. The syntax I am using is correct (as far as I know) in JavaScript, but I don't know if it would be null or not. Obviously, it starts out empty. That's sort of the point.

EDIT 2:

It looks like I can't accept answers either. Thanks to the both of you. It turns out I did need to call the constructor, despite some rather strange syntax errors I was getting earlier. Blowing your magic fairy dust on it made the problem go away.

# Answer
Seems like the list you are adding to is still null. In c# you would need to do something along `var intList=new List<System.Int32>` but I am not totally sure with JS.

I am more used to the array as a list element in JS, maybe take a look at this article

```
var intlist=new Array() //1) regular array. Pass an optional integer argument to control array's size.
intlist[0]=1;

```

Edit regarding your edit:

Just to clarify: There is a huge difference between a list beeing **null** or **empty**. When you are creating your var, you basically just tell the code that you want to use a list somewhere. This object ist still *null*, which means there is no memory allocated for it. You need to **create the object** (again in C#) usally by using the *constructor*. The list constructor will yield you an *empty* (but no longer *null*) list. To this list you may add objects.

This is your error, accoidng to this article about collections in unity your syntax is not wrong, but it is incomplete. See this snipped from the article:

```
var myList : List.<Type> = new List.<Type>();  // declaration
var someNumbers = new List.<int>();            // a real-world example of declaring a List of 'ints'
var enemies = new List.<GameObject>();         // a real-world example of declaring a List of 'GameObjects'
myList.Add(theItem);                           // add an item to the end of the List
myList[i] = newItem;                           // change the value in the List at position i
var thisItem = List[i];                        // retrieve the item at position i
myList.RemoveAt(i);                            // remove the item from position i

```

As you notice you need to initalize the list first via *constructor*, by calling it with the *new* keyword.
> 1 votes

# Answer
I got this fully functioning in Unity on an empty game object, you need to make sure you make the list with the new statement and also ensure you have the imports correctly defined.

```
#pragma strict
import System.Collections.Generic;
import System.Linq;

function Start () {
    var intlist : List.< System.Int32 > = new List.< System.Int32 >() ;
    intlist.Add(42);
    Debug.Log(intlist[0] ); //Outputs 42
}

```
> 0 votes

---
Tags: unity, javascript, unityscript
---


# Question
Title: When to use AI prediction in a Fighting Game
I am making a fighting game AI that can predict the player's next move using a N gram predictor. Once I have the prediction, when do I use it? Do I wait until the player makes a move and then use the prediction? What about distance from the player? How do I make the use of my prediction look realistic?

# Answer
> 1 votes
In that type of game the time frame is an important variable to consider, because the attacks/defenses must be well synchronized to be effective. I bet that is indeed one reason you've chosen to use that kind of predictor (i.e. based on continuous sequences). Even more, the decision about taking one countermeasure must be done based on the chances of the opponent taking a particular measure, and thus eventual errors (i.e. the NPC tried to block a strike that the opponent DIDN'T perform) make the result to look more realistic. Therefore, your prediction should be performed at the NPC's own agenda and in a time-based fashion (i.e. inside the game loop, whenever possible to avoid consuming too much processing power).

Just like the "moment" to take an action, the distance between NPC and opponent and the fighter's abilities are important variables. The predictor needs to consider the minimum distance in which either (NPC or opponent) can strike a punch or a special power, and the type of action taken also depend upon that. For instance, close blows usually require blocking and ranged shots can be avoided bu jumping over or counter attacking with a similar power/weapon.

In my experience, in game domains - and depending on the complexity desired, simple state machines or decision trees are useful and usually allow to achieve very good results without consuming too much computing resources.

---
Tags: ai, fighting-game
---


# Question
Title: Optimal number of work groups for compute shaders
In OpenGL, is there a way to dynamically determine the preferred workgroup size of the underlying hardware? Or at least, to approximate it using some queried metrics?

In OpenCL, you can do this using some implementation defined constants, but so far I wasn't able to find something similar for OpenGL.

# Answer
> 5 votes
In GPGPU, the preferred workgroup size usually is more dependent on the resources used by your compute shader, kernel, etc. and less on the GPU specs. A compute shader will have a maximum number of threads that could run in a multiprocessor based on the resources it uses (since the resources are shared among threads). This concept is one of the cores of compute shader optimization and is the so called Occupancy. In summary, the Occupancy is the ratio of the number of threads that can run in parallel in your compute shader and the maximum number that the GPU supports.

The differences in GPUs related with GPGPU are mainly the number of available multiprocessors and bandwidth. The scheduler of the GPGPU framework (CUDA, DirectCompute, etc.) has the job to assign the workgroups to multiprocessors in a way that compute shaders not depend too much of the GPU specs to scale well (that's the main reason that a boost in the GPU automatically boosts the code performance).

The role of the programmer is to write compute shaders whose workgroups use minimal resource. This is achieved by:

* Minimizing register usage;
* Minimizing shared memory usage;
* Minimizing conditional branches.

For NVidia GPUs you can use the CUDA Occupancy Calculator to check the occupancy based on the number of registers and shared memory used. The compiler outputs this data. Using this tool you can check any workgroup size and see which one gives the best occupancy. You can also use this in DirectCompute since in NVidia cards it is just a "wrapper" for CUDA functionality. Of course there is a lot of experimentation before getting the optimal number.

See this presentation for more details on GPGPU optimizations.

# Answer
> 0 votes
This is really dependent on what you do. there is no optimal number for anything. just on what you do.

I usualy pick something after what im doing. If i will have some shared memory, i try to stay within 32 threads per group. if im doing regular calculation i try to have a bigger group that that so i can get big chunks done rather than small.

If i have a large amount of data, i try to have really big groups so that i dont have to pass the data around to much.

So it all depends on the job!

# Answer
> -1 votes
According to the OpenGL 4.3 spec, you can at least query the maximum number of workgroups and the maximum workgroup size (MAX\_COMPUTE\_WORK\_GROUP\_SIZE) as well as the maximum number of invocations. I guess the max workgroup size is a good estimate for best performance.

```
GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS
GL_MAX_COMPUTE_WORK_GROUP_COUNT
GL_MAX_COMPUTE_WORK_GROUP_SIZE

```

all to be queried using glGetInteger.

---
Tags: opengl
---


# Question
Title: CreateRenderTarget returns 0x80070057 in big surface resolution
I have created the SLI merged desktop of three 1920x1680 monitors, so the desktop resolution is 5760x1080.

There is a 0x80070057 error, while calling CreateRenderTarget to create the RT\_Surface:

```
IDirect3DSurface9* _render_surface;
HRESULT hr = _device->CreateRenderTarget(
        _desktop_width * 2,
        _desktop_height + 1,
        D3DFMT_A8R8G8B8,
        D3DMULTISAMPLE_NONE,
        0,
        TRUE,
        &_render_surface, NULL);

```

It works OK with desktop resolution 1024x768, and the total resolution is 3072x768.

In http://msdn.microsoft.com/en-us/library/windows/desktop/bb174361(v=vs.85).aspx, it says

> If the method succeeds, the return value is D3D\_OK. If the method fails, the return value can be one of the following: D3DERR\_NOTAVAILABLE, D3DERR\_INVALIDCALL, D3DERR\_OUTOFVIDEOMEMORY, E\_OUTOFMEMORY.

and no description about 0x80070057.

> HRESULT: 0x80070057 (2147942487)
> Name: E\_INVALIDARG
> Description: An invalid parameter was passed to the returning function

Somebody please help me.

---

I tried to check MaxTextureWidth and MaxTextureHeigh in D3DCAPS9 structure as @mh01 indicated, and got the value 8192 both. And what I trying to create is 11520x1080.
So, my question is what effects the value of MaxTextureWidth and MaxTextureHeigh? VideoCard model or some setting in the BIOS?

---

I got the below information as @RayDey said, while turn on the debug level:

> Direct3D9: (INFO) :======================= Hal HWVP device selected
> Direct3D9: (INFO) :HalDevice Driver Style b
> Direct3D9: :Subclassing window 000d0612
> Direct3D9: :StartExclusiveMode
> Direct3D9: (INFO) :Using FF to VS converter
> Direct3D9: (INFO) :Using FF to PS converter
> Direct3D9: (INFO) :Enabling multi-processor optimizations
> Direct3D9: (INFO) :DDI threading started
> D3D9 Helper: Warning: Default value for D3DRS\_POINTSIZE\_MAX is 2.19902e+012f, not 9.2074e-316f. This is ok.
> Direct3D9: :WM\_ACTIVATEAPP: BEGIN Deactivating app pid=00000c9c, tid=00000728
> Direct3D9: :DoneExclusiveMode
> Direct3D9: :INACTIVE: 00000c9c: Restoring original mode (1680x1050x22x120) at adapter index 0
> Direct3D9: :*** Active state changing
> Direct3D9: :WM\_ACTIVATEAPP: DONE Deactivating app pid=00000c9c, tid=00000728
> Direct3D9: (ERROR) :Failed to create driver surface
> Direct3D9: (ERROR) :Error during initialization of surface. CreateRenderTarget/CreateDepthStencil failed
> Direct3D9: (ERROR) :Failure trying to create render-target
> D3D9 Helper: IDirect3DDevice9::CreateRenderTarget failed: E\_INVALIDARG

# Answer
> 3 votes
The GPU is telling you it can't create textures larger than 8192 in either dimension, and you're trying to create one that's 11520 wide. It's not going to work. This is likely to be a limitation of the GPU itself, not something you can work around with some hackery or a different driver. For instance, the GPU's texture units might only have enough bits in their address registers to store texture coordinates up to 8192.

# Answer
> 2 votes
A good (also widely used) workaround to this problem is to create multiple render targets of a size that your GPU supports, render your scene in pieces, and assemble on your back buffer(s). The downside to this is, you'll effectively render your scene N times (where N is your # of render targets), but with proper scene preprocessing, this may not be as bad as it sounds.

# Answer
> 0 votes
Check MaxTextureWidth and MaxTextureHeight in your D3DCAPS9 (using IDirect3D9::GetDeviceCaps or IDirect3DDevice9::GetDeviceCaps) - the most likely cause is that your MaxTextureWidth is 4096.

Even if it's larger it's still possible for a Create\* call to fail - you may not have enough video RAM, or your driver may not be allocate a large enough region of video RAM. I wouldn't expect an E\_INVALIDARG from that though.

You can specify D3DCREATE\_DISABLE\_DRIVER\_MANAGEMENT in your CreateDevice call which stipulates that "Direct3D will manage resources instead of the driver. Direct3D calls will not fail for resource errors such as insufficient video memory." What exactly happens if you do run out is another matter though, so it may be a bit risky. Plus, as I indicated above, this is most likely not a case of running out, so it's not really relevant.

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


title: Layer depth problem in XNA puzzle game

text:
# Question
Title: Layer depth problem in XNA puzzle game
I am working on puzzle game where tiles are needed to be dragged to their correct place, but at the time of dragging one of the textures goes behind the other texture. How can I bring the texture to the top?

```
       private void OnDraw(object sender, GameTimerEventArgs e)
       {
                         SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);

         // TODO: Add your drawing code here
        Color transp = Color.White;
     //   transp.A = 200;
        spriteBatch.Begin();

                   spriteBatch.Draw(Texture.piece[1],Texture.piecerect[1],null, transp,0,Vector2.Zero,SpriteEffects.None,1);

        spriteBatch.End();
    }

```

# Answer
If you use deafult `spriteBatch.Begin()`, then textures draw in order you call them. This mean you must simply draw dragging texture after background texture

```
                        spriteBatch.Begin();
                        spriteBatch.Draw(backgroundTexture, position,Color.White);
                        spriteBatch.Draw(draggingTexture, position,Color.White);
                        spriteBatch.End();

```

Another approach that i can suggest is to implement draw layers. One way to do that is to create an array from 0 to 5 for example and let 0 be top layer. Then assign to each texture layer number. Change texture layer in `Update` as you want. In `Draw` you then just simply iterate from 5 to 0 layer and draw coresponding to this layer textures.
> 2 votes

---
Tags: xna
---


title: Where to store OpenGL object id:s

text:
# Question
Title: Where to store OpenGL object id:s
When working with OpenGL, you often recieve integer id:s to keep track of OpenGL objects.

For example, representing a simple mesh, you may have a number of references to objects like so:

```
GLuint arrayBuffer;
GLuint elementArrayBuffer;
GLuint texture;

```

Having many meshes, the id:s add up quickly. Therefore my problem is, where it is most logical and efficient to store them?

**Alternative 1**

My first thaught was to hand out the id:s to corresponding game entities. Something along the lines:

```
class Entity {
public:
    GLuint arrayBuffer;
    GLuint elementArrayBuffer;
    GLuint texture;
    // Other methods...
}

```

Then having a render class:

```
// Create the buffers and textures and pass id:s to entity.
renderer.init(entity);
// Render with corresponding buffer/texture id:s stored in entity
renderer.render(projection, view, entity);

```

Where it then is easy enough, in the implementation of the render method, just picking id:s and render with them.

Some disadvantages is that this is a leaky abstraction, where OpenGL concepts are "leaked" to game entities. Which does not feel quite right. An advantage might be that the method supposedly is efficient. You do not have to find id:s, you know them for each rendering pass.

**Alternative 2**

Another alternative would be to store the id:s internally in the renderer. For example, an internal data struct:

```
struct RenderData {
    GLuint arrayBuffer;
    GLuint elementArrayBuffer;
    GLuint texture;
}

```

Then having an unordered map with references to each entity and corresponding RenderData:

```
std::unordered_map<unsigned int, RenderData> render_data;

```

Then in the rendering method, the correct render data is fetched from the map only by a unique id that is stored in each entity.

Advantages of this approach, is that it is less "leaky", where only the entity id is passed to the renderer, to know what data to use. Disadvantages may be slightly less efficiency, because of lookups in the unordered map?

I would greatly appreciate inputs on this, what approach to prefer, or if there are any other approaches out there?

# Answer
I would suggest the second approach. About optimisations:

1. Should follow the rule "Don't do that unless you have to" or your system will suffer from premature optimisation.
2. Should not harm the system architecture. The API and maintainability is always first priority, since in the long run it pays itself by letting us sleep well...
3. Should be preceded by profiling.

As an improvement, if in your system all entities have an associated `Renderer renderer` object or component, then you could do only `renderer.render(projection, view)` and can eliminate the map completelly from the process.

On the other hand, if the map is needed in your system it will not do any harm to performance since lookup on maps have constant expected time.

In summary:

* Always go for the path with better API, encapsulation and less mutability;
* Do optimisations in the lags of the system (which you will find by profiling).
> 1 votes

---
Tags: opengl, c++
---


# Question
Title: XNA DepthBias increases performance even when EarlyZ is turned off. Why?
My 3d scene consists of three main polygons:

The first and the second polygons overlap each other (have the same World matrix and use the same geometry), the third one is perpendicular to the first two and is positioned a few meters away from them. All three polygons are rendered with a forward shader that uses clip() function to do alpha cutoffs. As I read in a Radeon's article, this causes EarlyZ test to be turned off and my simple subjective tests proved it: I had around 480 FPS when the second polygon's texture was empty (resulting in clip being called in every pixel) and dropping to 415 when it had a colorful for-section square in it (see the picture).

I did try to make sure that Z-test happens: I tried drawing the second polygon first while "rising" it above the ground (polygon #2) and thus bringing it closer to camera - it changed nothing. I also tried removing clip() function from the shader and recieved an FPS boost just as expected. But obviously this produced incorrect results as the ground underneath the second polygon was never drawn as it always failed the Z-Test. So I decided to try using DepthBias to be able to draw two polygons one over another and have no depth-fighting. This is what MSDN writes about it:

> Sets or retrieves the depth bias for polygons, which is the amount of bias to apply to the depth of a primitive to alleviate depth testing problems for primitives of similar depth. The default value is 0.
>
> Property Value The amount of bias to apply to the depth of a primitive. The value ranges from 0 to 16 (inclusive).

When I finally managed to make it work, I surprisingly got a performance boost. Now the thing is I even managed to gain FPS applying it to the third polygon! This is how I render them to gain the best performance:

```
GraphicsDevice.RasterizerState = CCWLayer1;
DrawSecond(gameTime);
GraphicsDevice.RasterizerState = CCWLayer2;
DrawThird(gameTime);
GraphicsDevice.RasterizerState = CCWLayer3;
DrawFirst(gameTime);

public RasterizerState CCWLayer1 = new RasterizerState()
{
    CullMode = CullMode.CullCounterClockwiseFace,
    DepthBias = 0.005f,
};

public RasterizerState CCWLayer2 = new RasterizerState()
{
    CullMode = CullMode.CullCounterClockwiseFace,
    DepthBias = 1,
};

public RasterizerState CCWLayer3 = new RasterizerState()
{
    CullMode = CullMode.CullCounterClockwiseFace,
    DepthBias = 0.015f,
};

```

I now 525 FPS and it only drops down to 515 when I draw the huge colored square on the second polygon, which clearly shows that only one set of pixels is being drawn at a time in that particular place (which is similar to EarlyZ test!).

So here is the question: can anyone explain to me what is going on? If I could understand this system better I could make more use of it and gain even more FPS.

**Update: now I only draw the two polygons (no other geometry), both using clip(), the one with the colored quad (second) is always closer to the camera. With this code:**

```
DrawSecond(gameTime);
DrawFirst(gameTime);

```

I get 1.5 ms per frame. With this:

```
GraphicsDevice.RasterizerState = CCWLayer1;
DrawSecond(gameTime);
GraphicsDevice.RasterizerState = CCWLayer2;
DrawFirst(gameTime);

public RasterizerState CCWLayer1 = new RasterizerState()
{
    CullMode = CullMode.CullCounterClockwiseFace,
    DepthBias = 0.03f,
};

public RasterizerState CCWLayer2 = new RasterizerState()
{
    CullMode = CullMode.CullCounterClockwiseFace,
    DepthBias = 0.045f,
};

```

I get 1.2 ms.

NO BIAS:

BIAS APPLIED:

# Answer
You're using FPS is a profiling metric, which is a pretty bad idea because it is a non-linear measure. 525 FPS is about 0.001904 seconds per frame. 515 FPS is about 0.001941. That is a difference of about 0.000037 seconds, which is *significantly less than a millisecond*. Even between 480 (0.00208) and 525 FPS, that's only a difference of 0.000176 seconds (again, less than a millisecond).

With a timing delta that small and with the very limited set of information you've provided, it's quite likely that the differential is entirely due to the fact that you are drawing additional geometry and have provided different inputs to the graphics pipeline, causing it to do different things. Especially since your explanation makes it sound like you stopping using `clip()` (which will be an improvement) and *then* applied the bias to solve the depth-fighting problems.
> 1 votes

---
Tags: xna-4.0, performance, depth-buffer, clipping
---


# Question
Title: SFML image extension for best performance
I am using SFML library in my 2D game.

The Texture Class has a method to load an image from file:

```
Texture.loadFromFile("image.*")

```

Which file extension should I use to achieve best performance?

# Answer
## Original texture format does not affect in game performance

There may be a small loading time difference, but that is likely dependent on what system you are running on.

**Use what ever texture format you and your artists are comfortable with. I would personally use png because it is losslessly compressed.**

Don't fret over a few milliseconds on texture loading, you are likely to save more time by using your own sprite sheets.

**If you really want to figure it out, profile all the different image loading techniques.**
> 4 votes

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


# Question
Title: How to create and populate a 2D Texture Arrays in DirectX11
I have generated a bunch of `ID3D11ShaderResourceView` that are a 2D textures that have a depth map screen shot for my lights shadows. I would like to take all of these textures and put them into a single 2D Texture Array.

I have seen examples of how to create a 2D Texture array like in this question here but I don't know how to copy the data to the newly created texture array.

# Answer
You can use `CopySubresourceRegion` to copy data between textures. "Subresource" means a combination of mip level and array index, so here you would copy to the subresource corresponding to the desired index in your texture array.

However, it's best to avoid copying data between textures if possible, as it does take time. Instead of rendering to a bunch of 2D textures and copying into the array, it would be faster to render directly to the array. You can do this by creating a render target view that points to a specific subresource in the texture array.
> 1 votes

---
Tags: c++, textures, directx, directx11
---