title: Algorithm to generate multifaced cube?

text:
# Question
Title: Algorithm to generate multifaced cube?
Are there any elegant soloution to generate a simple-six sided cube, where each cube is made out of more than one face? The method I have used ended up a horrible and complicated mess of logic that is imopssible to follow and most likely to maintain. The algorithm should not generate reduntant vertices, and should output the indice list for the mesh as well.

The reason I need this is that the cubes vertices will be deformed depending on various factors, meaning that a simple six-faced cube will nto do.

# Answer
> 3 votes
The way I'd approach this is to first write an algorithm that generates the mesh for just one side of the cube - that is, just a square, subdivided into as many polygons as you want. This should be easy to get right since it's just a grid.

Run this six times to generate the six sides of the cube, then concatenate all the meshes together and weld the shared verts at the edges and corners. The welding can be accomplished by explicitly keeping track of the edges and corners of each square during the initial generation and concatenation phases and hard-coding the logic for which ones should be welded together, or it can be done by a generic algorithm that detects pairs of vertices within a certain distance of each other and welds them. (For the latter you'd probably want to build an octree or something to accelerate queries for nearby vertices, else the whole thing will be O(n^2), not good if you subdivide finely and have a lot of vertices.)

---
Tags: graphics, algorithm
---


# Question
Title: Loss of texture detail in XNA (Banding 16 bit issue)
I'm loading in a background texture for my game, it's not vert detailed, it's just there too add some variance. The problem is that there looks like a large reduction in detail. I've included images below so you can see what I'm talking about. What would cause this to happen and how can I get my detail back?

More info:
Verticies are `VertexPositionTexture`
Load method `Texture2D.FromStream`
Effect `BasicEffect`

Also the project is a Silverlight/XNA mix

Source Image:

Image from game:

Note: the images don't match up completely but you should get the idea.

# Answer
Your texture is a 32 bit texture. Somewhere between loading it and displaying it, it is getting downsampled to 16-bits (or some other low bit-depth). The loss of precision gets rid of the smooth gradients and gives you bands of colour like that.

None of the things you have mentioned (loading it with `LoadStream`, drawing it with `BasicEffect` with that vertex format) will reduce precision like that.

My bet is that you're rendering to a 16-bit backbuffer. I can get a similar result by setting:

```
graphics.PreferredBackBufferFormat = SurfaceFormat.Bgr565;
graphics.IsFullScreen = true;

```

You can verify your *actual* backbuffer format (note that what you specify to `GraphicsDeviceManager` is just a preference) by checking:

```
GraphicsDevice.PresentationParameters.BackBufferFormat

```

It's also possible you're using a low-precision render target somewhere.
> 4 votes

# Answer
By default, in Windows Phone 7 all apps use 16 bits per pixel graphic mode. To switch it to 32 bits, see here: https://stackoverflow.com/a/10313783/126995. This is only available since WP 7.1 Mango, but since every WP7 device can be upgraded to WP 7.1, it's no big deal.
> 3 votes

---
Tags: xna, textures, windows-phone-7
---


# Question
Title: How would I get this to UV map correctly?
Alright so I have my code to draw out a big landscape using C++ and DirectX. I had it textured with one texture and then needed to add more. I saw people doing it where they had 1 texture image and the image contained 2 textures. Thats what I made, it's a 256x128 image. My problem now is that since my terrain automatically generated the coordinates to UV map 1 texture now it is displaying both textures. I need to make it so when the height of the world is high enough it is 1 texture and everything under is another texture. My code for the UV coordinates,

Vertices\[y * WIDTH * x\].U = x / 1.28;

Vertices\[y * WIDTH * x\].V = y / 1.28;

those are my mapping coordinates, X is the current X value of the vertice it is drawing and the Y value is its current y position. The heightmap is 128x128 so I divided by 1.28 to make it so that each polygon had the texture UV mapped on it. The height is calculated as well since I am loading a heightmap and im trying to get it so when it is high enough it UV maps 1 half of the image and if it is the other it UV maps the other side of the image. Someone please help!

# Answer
The texture you described with two textures packed in one is called a texture atlas. That can be useful for certain things, but I don't think it's an appropriate choice in this case, because as you found out, it breaks tiling.

What you probably want is called multi-texturing or texture splatting (those are some good terms to google). This involves setting up two separate texture objects and binding them both when you want to draw your terrain, then using a shader that samples both textures and blends between them based on height (or some other factor, such as vertex color).

Which version of Direct3D are you using, and how much experience with shaders do you have? Based on that, I might be able to give you some more specific help. I'm not very familiar with Direct3D 9 and below, though.
> 1 votes

---
Tags: c++, directx, uv-mapping
---


# Question
Title: How can I make a tile appear on top of another without completely blocking the tile below?
Making a small RPG with libdgx just for learning about how to draw tiled maps and move around in them. I've got the tiles drawn and OrthographicCamera stuff figured out so I can see my world. My question is, how can I put character on a tile, so that he appears to be standing on the tile?

My idea is to give each tile a separate texture that has the character drawn on the tile. So for example, I would have grass.png and then I would have grass-hero.png. And then based on where the hero is upon the next render loop, if the hero has moved to a tile that was previously "grass", instead this time draw "grass-hero".

Example:

Now, I haven't done it yet, but I'm pretty sure that would work. My question is, is there some way that I can bypass having to use a separate "combined" tile like grass-hero, and just have my hero walk on top of the grass tile? I imagine if I use another tool like .NET Paint I could "cut" the hero out of the black background and make the background transparent, but I still don't know how to make one tile appear on top of another.

To provide some abbreviated semi psuedo code, let me show what I have:

**GameScreen (implements Screen)**

```
@Override
public void render(float delta)
{
    worldrenderer.render();
}

```

**WorldRenderer**

```
public void render()
{
    spriteBatch.begin();
    drawTiles();
    drawHero();
    spriteBatch.end();
}

private void drawTiles()
{
    for (Tile tile : world.getTiles())
    {
        switch(tile.getTileType())
        {
             case GRASS:
                 spriteBatch.draw(grassTexture, tile.getPosition());
                 break;
             case FOREST:
                 spriteBatch.draw(forestTexture, tile.getPosition());
                 break;
             case STONE:
                 spriteBatch.draw(stoneTexture, tile.getPosition());
                 break;
        }
    }
}

private void drawHero()
{
    Hero hero = world.getHero();
    spriteBatch.draw(heroTexture, hero.getPosition());
}

```

# Answer
> 7 votes
Judging from a quick look at the libgdx wiki's SpriteBatch entry, alpha blending is on by default.

> Blending is enabled by default. This means that when a texture is drawn, translucent portions of the texture are merged with pixels already on the screen at that location.

This means that you can do what you said: open the Hero texture in Paint .NET and "delete" the background portion. Your render method already draws the sprites in the proper order (world then hero)!

# Answer
> 1 votes
I'm not familiar with libgdx specifically, but in general terms what you probably want here is to use alpha blending. You'd add an alpha channel to your hero texture, which would contain white in all the pixels where the hero is, but black in all the pixels that should be transparent. You'd then have to enable blending when drawing the hero sprite. The graphics hardware will then use the alpha channel to composite the sprite over the background.

---
Tags: tiles, libgdx, rpg, grid, transparency
---


# Question
Title: Can I limit the number of shader units used by my video card?
Can I limit the number of shader units used by my video card? (A shader unit is the part of the hardware which can execute a shader program, where each unit runs in parallel).

I'm interested in this in an OpenGL context, i have an ATI 5770 just in case that you need to know.

# Answer
No, there is no way from OpenGL to change how your GPUs distribute your shaders across its internal computing resources. The job of the driver is to find an optimal distribution for the work you provide it.
> 3 votes

---
Tags: opengl, shaders, debugging
---


# Question
Title: What is a trainer from a coder prospective?
What steps usually takes or modify a trainer?

How a trainer can change the way a game behaves?

Edit: with the word *trainer* I mean the applications, usually a single executable, that can unlock and give extra points and features during a gameplay, kind of a series of cheats that you can activate with this executable.

# Answer
I've never written a trainer myself, but I would guess that they operate by editing specific locations in the game's memory. Access to the game's address space can be gained by DLL injection or by using a debugger-style API like `WriteProcessMemory`.

To alter specific aspects of the running game (health, points, resources etc.) you have to figure out exactly where in the game's memory this data is stored. In practice, the location of this data probably varies from one session to the next (due to nondeterministic heap allocations, etc.), so really you have to figure out how to *find* that data starting from a reliable address (such as a global variable in the data section of the game's .exe) and following pointers, etc. This is the hard part.

Once you know where the data is, you just overwrite it with your desired value.
> 3 votes

---
Tags: behavior
---


title: XNA Multisampling only for 3D

text:
# Question
Title: XNA Multisampling only for 3D
I am working on a game which consists of 3D elements and a 2D GUI. I have it working properly, but I want to enable multisampling for only the 3D parts, and not the 2D Textures. Otherwise, the GUI icons become blurred.

Here is the code for my `Draw` method

```
    protected override void Draw(GameTime gameTime)
    {
        graphics.PreferMultiSampling = true;
        graphics.ApplyChanges();

        GraphicsDevice.Clear(Color.Black);

        GraphicsDevice.SamplerStates[0] = SamplerState.PointWrap;
        GraphicsDevice.DepthStencilState = DepthStencilState.Default;

        foreach (Element e in Elements)// 3D part
        {
            e.Draw(GraphicsDevice, camera);
        }

        graphics.PreferMultiSampling = false;
        graphics.ApplyChanges();

        spriteBatch.Begin();
        UIM.Draw(GraphicsDevice, spriteBatch);
        spriteBatch.End();//

        base.Draw(gameTime);
    }

```

Using this code, I get an exception because all of my `Texture2D`s dispose for some reason.

Is there a way to change the MultiSampling in the middle of the `Draw` method?

# Answer
> 1 votes
Multisampling is a property of the backbuffer. So: no, you cannot change it mid-draw.

Where you call `ApplyChanges` you're causing the graphics device to get torn down - you should never call this during `Draw`.

One thing you could do is render your UI to a render target without multisampling. Or alternately render your 3D geometry to a render target *with* multisampling (and disable multisampling for your backbuffer).

Note the `preferredMultiSampleCount` parameter to `RenderTarget2D`'s constructor (MSDN).

It's worth pointing out that mutlisampling (as opposed to super-sampling with a linear texture filter) *shouldn't* cause your sprites to become blurry - because it only affects the edges of polygons - not their textures! (details here).

It's possible that you've got a sub-pixel alignment problem. On that note, it might be interesting to pass `SamplerState.PointClamp` to `SpriteBatch.Begin` and see what happens.

---
Tags: xna, c#, graphics, directx, antialiasing
---


title: My hlsl shader cannot unroll a loop?

text:
# Question
Title: My hlsl shader cannot unroll a loop?
I have this shader:

```
   texture tex;
   sampler2D s = sampler_state {
      texture = <tex>;
   };

   int tWidth = 1;
   int tHeight = 1;
   int blurLength = 3;

   float4 ps_main(VS_OUTPUT Input) : COLOR0
   {
      float weight = 1.0 / (blurLength * blurLength);
      float2 pxSz = float2(1.0 / tWidth,1.0 / tHeight);
      float4 color = Input.Color * tex2D(s, Input.TexCoord.xy);
      float4 outC = 0;
      int x = 0;
      int y = 0;
        int numSubtr = (blurLength - 1) / 2;
        x -= numSubtr;
        y -= numSubtr;
        int count = 0;
        for(int i = x; i < x + blurLength; ++i)
        {
            for(int j = y; j < y + blurLength; ++j)
            {
                outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(i * pxSz.x,j * pxSz.y)) * weight;
            }
        }
      return outC;
   }

```

When I load it I get:

What could be wrong? (using hlsl ps 2.0 I think)

Thanks

# Answer
> 4 votes
You need to declare `blurLength` as a `static int` for this to work. When unrolling a loop, the iteration count has to be a compile-time constant; without the `static` on there, the compiler has to assume you might change the value of the parameter at runtime.

# Answer
> 0 votes
You may be running out of instructions of one or the other flavor, according to MSDN, SM2.0 is quite restricted. The diagnostics of the shader compiler is rather horrible at times.

> Shaders have restrictions for maximum instruction counts. Total Instruction slots: 96 (64 arithmetic and 32 texture).

---
Tags: c++, shaders, hlsl
---


# Question
Title: RPG Monster-Area, Spawn, Loot table Design
I currently struggle with creating the database structure for my RPG. I got so far:

tables:

* area (id)
* monster (id, area.id, monster.id, hp, attack, defense, name)
* item (id, some other values)
* loot (id = monster.id, item = item.id, chance)
* spawn (id = area.id, monster = monster.id, count)

It is a browser-based game like e.g. Castle Age. The player can move from area to area. If a player enters an area the system spawns, based on the area.id and using the spawn table data, new monsters into the monster table. If a player kills a monster, the system picks the monster.id looks up the items via the the loot table and adds those items to the player's inventory.

First, is this smart? Second, I need some kind of "monster\_instance"-table and "area\_instance"-table, since each player enters his very own "area" and does damage to his very own "monsters". Another approach would be adding the / a player.id to the monster table, so each monster spawned, has it's own "player", but I still need to assign them to an area, and I think this would overload the monster table if I put in the player.id and the area.id into the monster table.

What are your thoughts?

**Temporary Solution**

```
monster (id, attackDamage, defense, hp, exp, etc.)

monster_instance (id, player.id, area_instance.id, hp, attackDamage, defense, monster.id, etc.)

area (id, name, area.id access, restriction)

area_instance (id, area.id, last_visited)

spawn (id, area.id, monster.id)

loot (id, monster.id, chance, amount, ?area.id?)

```

---

An example system-flow would be: Player enters area 1:

* system creates area\_instance of type area.id = 1 and sets player.location to area.id = 1

If Player wants to battle monsters in the current area:

* system fetches all spawn entries matching area.id == player.location and creates a new monster\_instance for each spawn by fetching the according monster-base data from table monster. If a monster is fetched more than once it may be cached.

If Player actually attacks a monster:

* system updates the according monster\_instance, if monster dies the instance if removed after creating the loot

If Player leaves the area:

* area\_instance.last\_visited is set to NOW(), if player doesn't return to data area within a certain amount of time area\_instance including all its monster\_instances are deleted.

# Answer
The problem will be dealing with instances of monsters, especially as you can have many monsters of the same type. The easiest way IMO would be to have a special table that deals with instances, and have a limited number of instances per area, say 10.

This doesn't stick with what is considered 'good' SQL but it should work providing you can limit the instances :

Table AreaMonsters { player.id, area.id, monster1.id, monster1.currHP, monster2.id, etc... }

This will allow you to insert a new line with all the data for an area, and it will be persistent throughout the game. The only problem really is the limit to instances.

*** Original Answer ***

From looking at your tables, the setup seems ok, but beware of using reserved words (like count).

I'm not too familiar with Caste Age, but why cant you just keep the instances client-side? This shouldn't pose a problem if each player has their 'own' area instance.

A problem would be the persistance of the data during the game, can the player only be in one area at once? Will the damage he dealt be forgotten once he leaves?

Another question would be whether each monster keeps his current health. If this is not the case it could be possible to just keep track of the number of each monster in the area instance, and assume that when the player starts attacking, the monster has full health.
> 3 votes

# Answer
Your suggestion and 3nixios's answers are not properly normalized. Here is a table schema that might do the trick:

```
table area
    id, name
    // might be better kept in a separate table restriction and linked via the table areaRestrictions
    access restrictions

table monster
    id, name, exp, attack, defense, maxHp

table areaMonsters
    id
    areaID
    monsterID
    count // or some other spawn related data

table monsterItems
    id
    monsterID
    itemID
    dropChance

table areaInstance
    id
    characterID
    areaID
    lastVisit // timestamp, default NOW()

table monsterInstance
    id
    monsterID
    areaInstanceID
    hp // plus other instance instead of type related data

```

**Character (charID) enters an area (aID)**

* Check if there is an entry in areaInstance with characterID=charID and areaID=aID (and lastVisit sufficiently high in case you don't want to delete obsolete records)
    + If a record exists, use it and set lastVisit to NOW()
    + If not:
        - Create a new record in areaInstance
        - Fetch all the entries in areaMonsters
        - Create new records in monsterInstance according to the entries in areaMonsters

**Character looks for enemies in an area**

* Let the character enter the area, if that has not been done before (see above)
* Fetch all entries in monsterInstance with the relevant areaInstanceID
* Let the player choose a target / select a target by some algorithm

**Player fights a monster**

* Reduce hp in the relevant monsterInstance record.
* If the monster dies:
    + Fetch all entries in monsterItems to determine loot
    + Delete the monsterInstance record

**Player does not visit an area for some time**

* Have a background process check periodically if there are any areaInstance records with lastVisit too long ago. Delete these records.
> 4 votes

---
Tags: rpg, databases, data-structure
---


title: Creating custom collision map for 2D

text:
# Question
Title: Creating custom collision map for 2D
I have a 2D level that I have built in my map editor, and I was wondering the best way to create a collision map for it.

I have a collision map layer in my map editor, which saves each node (for example, a rectangle would be just 0,0 0,50 50,60 0,60)

I was just wondering how I could take my node locations and convert it to a collision map for Unity.

Thanks! I feel this has to be able to be done, I can think of how I would do it in flash... but I am not sure how to manipulate it in Unity.

EDIT PICTURE: So I have a node at each one of these red dots (surrounding my terrain lets say) I want to build a collider from those nodes

# Answer
I thought since these types of questions seem to show up now and then I'd explain myself a bit more in detail.

Assuming you have a 2D level from a heightmap like in the image without any "overhanging" geometry:

What we want to do is check if point p is below the line, in which case we have a collision at l\_p. To accomplish this we interpolate v1.Y and v2.Y value to check the height of the line at p.X. If this l\_p.Y is larger than p.Y then there is a collision.

* Start by checking if v1.X \<= p.X \< v2.X
* calculate interpolation amount (a), ie, how large part of v1.Y and v2.Y respectively should be used where a = (p.X - v1.X) / (v2.X - v1.X)
* calculate interpolated Y by y = (1-a) * v1.Y + a * v2.Y
* if y \>= p.Y then there is a collision
* If needed solve interpenetration by setting p.Y = y
* IMPORTANT: If you apply an impulse to the body at this point make sure to check that there is actually a *closing velocity* ie that there is a velocity pointing downwards in this case. Otherwise you might get another collision reported next frame sending the body downwards again.
> 2 votes

---
Tags: 2d, collision-detection, unity
---


# Question
Title: How to keep balance / Unlock items / achievement rules
I'm working on an engine for a game, too learn javascript and just because its fun. I'm a flashdeveloper, I know how to build websites. Now making games is a different challenge, javascript is a challenge, but I'd love to learn how to structure code and what patterns are common. I dont mind if the game ever finish, I'm mostly interested in the programming part of it. I dont have a particular endresult in mind, so I'll see where it takes me.

I currently have a system where you can buy items. The items cost a specified amount of gold, silver, diamonds etc. When you have selected and bought the item, it takes time before getting rewarded. When time is over, you are getting rewarded with other properties (gold, energy, diamonds). For example, you can buy an apple for 50gold, It takes a minute, you get rewarded with 75energy. Or if you take a run, it cost 50energy, it takes 5minutes, reward is 25gold and 25silver. These definitions is what i call *actions*. Currently I already have a system where this already works and I can define as much actions with as much properties as I want.

The definitions I have kinda looks like this:

```
{id:101, category:544, onInit:{gold:-75}, onComplete:{energy:75}, time:2000, name:"Apple", locked: false}
{id:102, category:544, onInit:{gold:-135}, onComplete:{energy:145}, time:2000, name:"Banana", locked: false}
{id:106, category:302, onInit:{energy:-50, power: -25}, onComplete:{gold:100, diamonds:2}, time:10000, name:"Run", locked: false}
{id:107, category:302, onInit:{energy:-70, silver: -55}, onComplete:{gold:100}, time:10000, name:"Dance", locked: false}
{id:108, category:302, onInit:{energy:-230, power: -355}, onComplete:{gold:70, silver:70}, time:10000, name:"Fitness", locked: false}

```

Now, I would love to add a system where I can lock/unlock the actions using achievement rules. Lets say, if you buy 10 apples, you unlock a new action, like bananas which cost more, and reward more. In the future I maybe want to restrict achievements and actions to levels. I am kinda stuck how to structure this.

I have 2 questions:

1. Which patterns are used to define achievements? How/where are they defined? Should it be part of the action, or should it be a separate controller? Is it a good idea to register all completed actions to it? I think I want multiple types of achievement rules, Id love to hear some ideas how to develop it.
2. How do you create/find a good balance, so the user does not get stuck or can cheat by repeat a pattern of actions to get too much rewards. I know there is not a simple answer and i'm lacking of a good game-concept, but I wonder if anyone created such a game and how you dealed and played with it.

# Answer
> 1 votes
Balancing is too vague a problem to be answered here, but this might work for your first question:

* Define actionLog, an array of the form actionID =\> numberOfFinishedActionsOfThatType data structure to store how often the player has already completed each action.
* Add a property called "restrictions" to your actions. Restrictions is a list, with each restriction being an array with the properties "type" and "parameters".
* Before a player starts an action, go through all the restrictions of that action to see if they are met.

For example, the checkIfRequirementsAreMet method might look something like this:

```
restrictionsAreMet = true;
for each (var restriction in action.restrictions)
    switch(restriction.type) {
        // your achievement case
        case "numberOfActionsFinished":
            if(actionLog[restriction.parameters.action] < restriction.parameters.n) {
                restricitonsAreMet = false;
            }
            break;
        // some other type of restriction
        case "level":
            if(character.level < restriction.parameters.n) {
                restricitonsAreMet = false;
            }
            break;
    }
}
return restrictionsAreMet;

```

Note that this is a very crude and straight-forward way of implementing achievements and restrictions. If you want to improve on this suggestion, you might want to think about some of the following options as well:

* Define an class Restriction with a method "met()" that takes the game state as a parameter and returns either true or false. Subclass Restrictions to define specific types of restrictions, like NumberOfActionsRestriction, LevelRestriction, etc.
* Define a class Action and raise events whenever a player finishes an action. Then define event listeners in other game components to react to these events in any way they want.
* For example, you could define Achievement objects that listen to Action.onFinished and increase a counter property every time a relevant action was finished. You could store these Achievement objects as a list in your GameState data structure that is passed to Restrictions's met() method, so that your restrictions can access these Achievements.

Read http://www.javascriptkit.com/javatutors/oopjs.shtml or some other tutorial to get started with object-oriented programming in JS.

---
Tags: design-patterns, achievements
---


title: Xna Loading Screens

text:
# Question
Title: Xna Loading Screens
I'm making a 2D XNA game. I'd like to implement loading screens when stuff has to load for a while. Like when I login to an account, connect to the server, and generate worlds. I'm pretty sure it needs to be multithreaded, because I want to be able to do something like "Generating World 10%...11%...".

```
  GenerateWorld()
  {
       //Call StartLoading("Generating World"); or something
       //Starter generating, Updating progress...
       //End loading screen and fade into world
  }

```

Help appreciated, I'm new.

# Answer
You don't need multi-threading at all, but some knowledge in parallel programming could be useful.

Do your load in batches in your game loop and you'll be fine.
> 1 votes

# Answer
I'd highly recommend looking at the following guide: http://www.spikie.be/blog/page/Building-a-main-menu-and-loading-screens-in-XNA.aspx

I had a look at it yesterday, and pulled out the loading screen code for a project I was working on, think it might be of help to you.
> 3 votes

# Answer
I wouldn't really call multithreading overkill. It at least doesn't lock up the game/system. So what I would do is have a counter for percentage, load everything in a thread, and for each item loaded increase the counter (by 1/number of items for 0-1 scale). Then, in the draw function, just have something draw current percentage. Then, once the data is finished loading, set a flag to true saying that the game has been loaded (this is important so that you do not crash the game because it wants to draw what hasn't yet been loaded).
> 1 votes

# Answer
**Disclaimer:** This is kinda off-the-cuff advice, so take it as such.

If you're trying to multi-thread, it might be overkill for a loading screen. Unless you have a cool loading screen like (I think Fallout's) install screen, where you play Arkanoid while it installs!

You can usually do this with something simple, like using a timer on a short (1 second?) interval to update the "loaded" percentage, while your main application loads what you need.

Plus, if your game is small enough, you won't even need a loading screen!
> 0 votes

# Answer
I've done something like this:

* A class ContentLoaderSpool that have:

. One Dictionary keyed by the paths of the files to load, with the value as the instance of the content loaded (Texture2D, Song, Video and so);

. One property to flag if there's some content still need to load;

. A method asking for start loading the content. It iterates through the Dictionary and populates their values. This method works in a parallel thread with high priority. While this method is running, the main game loop continues normally.

The game loop can grab informations of the Spool, to update one progress bar or see if the entire collection of content were loaded and finally change to the next screen.
> 0 votes

---
Tags: xna, c#, multithreading, loading
---


title: What is "streamlined" user interface?

text:
# Question
Title: What is "streamlined" user interface?
I have come across this term "streamlined" user interface, and I wonder how is it different from other user interface type? What is the different between "streamlined" and "non-streamlined" user interface?

# Answer
Conceptually, a streamlined UI is one where every UI element is exactly where the user wants it at the exact moment that the user needs it, and is not visible when the user doesn't need it.

Obviously, what constitutes "streamlined" is semi-subjective. There are some objective measurements, and there are a lot of objectively *wrong* things you can do with UI design. People generally design a streamlined UI either though solid UX experience and design principles, or by sitting someone down and letting them play it, then seeing where they have trouble.
> 13 votes

# Answer
Not having the source from which you read the terminology, I'm going to guess it was simply referring to the literal definition of the word "streamlined."

> stream·lined \[streem-lahynd\] adjective
>
> 1. having a contour designed to offer the least possible resistance to a current of air, water, etc.; optimally shaped for motion or conductivity.
> 2. designed or organized to give maximum efficiency; compact.
> 3. modernized; up-to-date.

That is, a streamlined interface would be one that is efficient, not clunky, intuitive, and gets the user exactly what they need without overwhelming them. It's often used as a "buzzword" with others like "web 2.0", "blogosphere", and "rich". These words are sometimes thrown into conversation online in an attempt to sound trendy.
> 9 votes

---
Tags: ui-design
---


# Question
Title: Can I include PCM audio data in a commercial application?
For certain reasons, I need raw audio data in my application. I would convert certain sounds to a PCM format (at development time), and store & load these PCM files in my game.

PCM stands for Pulse Code Modulation, and as far as I can see, it is a representation of signal, and thus cannot be patented by anyone. Only formats can be patented I suppose (e.g. WAV, which relies on PCM), but PCM sequence of bits cannot be.

So if I include PCM data in my application package, I don't violate any patent, do I?

I'm developing for Android, by the way.

# Answer
Sure you can. You can also use WAV files, they are not patent protected. The formats themselves can't be protected by patents, however algorithms used in certain formats can. For example MP3 is affected by that.

But there are also other, probably better formats for that purpose:
**Ogg Vorbis**: Open & lossy codec, very small size, comparable to MP3
**FLAC**: Open & lossless codec, not as small as OGG or MP3 but still a lot (~50%) smaller than the PCM data while retaining the same quality.
> 2 votes

---
Tags: android, audio, patents
---


title: OpenGL in xcode 4

text:
# Question
Title: OpenGL in xcode 4
I'm just getting started with OpenGL with lot's of ideas on my head that i want to experiment, i started reading the OpenGL Superbible book which looks amazing but i am having a super hard time making any of the examples work on xcode 4.

Can anyone tell me how to set up a project to run any of this OpenGL Examples?

Thanks!

BTW: I am reading the 4th edition and not the 5th one since someone recommended me doing so.

# Answer
> 0 votes
I can see that you are trying to learn OpenGL 2.1. The good thing about this release is that it easy to get started with and get something up on the screen. The bad thing about OpenGL 2.1 is that things has changed quite a bit in OpenGL 3.x and 4.x, so when you want to take your graphics programming a step further, you need to learn a few more things.

Anyway there is a lot of tutorials about how to setup XCode with OpenGL 2.1. A good one is:

---
Tags: opengl, xcode
---


# Question
Title: Cannot build project for Xbox, using XNA
I'm trying to build a project for Xbox, and when I try to Package as an XNA Creator's Club Game I receive the following errors:

The best overloaded method match for 'Pong.MessageBoxScreen.MessageBoxScreen(Microsoft.Xna.Framework.Game, string)' has some invalid arguments.

Argument 1: cannot convert from 'string' to 'Microsoft.Xna.Framework.Game'

Argument 2: cannot convert from 'bool' to 'string'

```
        /// <summary>
    /// Event handler for when the Unlock Game menu entry is selected.
    /// </summary>
    void UnlockMenuEntrySelected(object sender, PlayerIndexEventArgs e)
    {
 #if XBOX
        try
        {
            Guide.ShowMarketplace(e.PlayerIndex);
        }
        catch (GamerPrivilegeException gamerPrivilegeException)
        {
            const string message = "Please use Xbox Live account.";

            MessageBoxScreen promptForPurchase = new MessageBoxScreen(message, false);
            ScreenManager.AddScreen(promptForPurchase, e.PlayerIndex);
        }
 #else
        const string message = "Unlock Full Game (Xbox Only)";
        MessageBoxScreen unlockMessageBox = new MessageBoxScreen(Game, message,      false);
        ScreenManager.AddScreen(unlockMessageBox, e.PlayerIndex);

 #endif
    }

```

Everything within the #if XBOX area is grayed out, I suppose because it is surrounded by that tag.

What do you think is suddenly causing these issues, and how can I correct it?

# Answer
> 4 votes
Based on the exception, it appears this line is at fault:

`MessageBoxScreen promptForPurchase = new MessageBoxScreen(message, false);`

You'll see that the error message tells you exactly what is wrong. You are passing arguments that are invalid for that constructor. You need to pass a `Microsoft.Xna.Framework.Game` object as the first argument and a `String` as the second argument.

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


title: Starting a game project

text:
# Question
Title: Starting a game project
> **Possible Duplicate:**
> Where can I find indie “teams”

I already know this is probably not the right place to ask and, if you think this question does not belong here, please delete it. So, the question is,

If I decided to start a video game project, is there a place where I can sort of "recruit" people who might want to join me and develop the game together?

Thanks in advance.

# Answer
If you have no actual working game at all yet, then you are looking for recruitment at the wrong time.

If you want people to join up, you need something up and running. You need a basic proof of concept. You need to show that you can get stuff done. You need to show that you are serious. You need to be able to catch their interest.

Absolutely nobody is interested in joining your team (presumably with you as a leader) if you have zero anything to show off. You have no way to actually get people interested if you have nothing to show them. There are a million and six joes going around saying "I have an idea please help me make it come to life." There are very few people who can say "look here at this awesome prototype I made that you can play right now and see how awesome it is first hand, so who wants to help make it more awesome?"

It doesn't matter much if what you can build is not polished. Nobody is going to expect you to have any kind of real art, nor to have a production-quality game engine, nor even a final version of the core game mechanics prototyped. If you saw what prototypes of your favorite AAA games looked like when they were pitched to publishers, you'd laugh quite hard; they look like crap, hardly look like a game at all, and certainly look like nothing even remotely close to the final product. However, they are still playable, interactive, and show off the core elements of the game, at least enough so that people can make an educated judgment about whether the game will be fun or interesting.

If you're not in a position to even make a basic prototype in Unity or something, you're not at a point where you should be looking for teammates. If you can't do even the simplest of things on your own, you need to improve your own skills, not drag down a team of people with your lack of skills. Make some small, simple practice games on your own, get some experience, and build up your skillset first. Then join another existing team as a junior member rather than trying to start and lead your own team, so that you can build your team skills and slowly work up to leadership skills. Only once you've got a solid foundation of game development/production skills and a solid foundation of teamwork/leadership skills do you have business trying to form a new team. Not saying that to be mean, but rather just to save you from a lot of potential grief.
> 2 votes

---
Tags: project-management
---


title: My blur gets ugly when radius too high

text:
# Question
Title: My blur gets ugly when radius too high
I have the following h and v blur:

Horz

```
  texture tex;
   sampler2D s = sampler_state {
      texture = <tex>;
   };

   int tWidth;
   int tHeight;
   float blurSize = 9.0;
   float4 ps_main(VS_OUTPUT Input) : COLOR0
   {
      float2 pxSz = float2(1.0 / tWidth,1.0 / tHeight);
      float4 outC = 0;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(-4.0 * pxSz.x * blurSize,0)) * 0.05;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(-3.0 * pxSz.x * blurSize,0)) * 0.09;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(-2.0 * pxSz.x * blurSize,0)) * 0.12;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(-pxSz.x * blurSize,0)) * 0.15;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,0)) * 0.16;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(pxSz.x * blurSize,0)) * 0.15;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(2.0 * pxSz.x * blurSize,0)) * 0.12;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(3.0 * pxSz.x * blurSize,0)) * 0.09;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(4.0 * pxSz.x * blurSize,0)) * 0.05;
      outC.r = 0;
      outC.g = 0;
      outC.b = 0;
      outC.a *= 0.8;
      return outC;
   }

```

vert

```
  texture tex;
   sampler2D s = sampler_state {
      texture = <tex>;
   };

   int tWidth;
   int tHeight;
   float blurSize = 9.0;
   float4 ps_main(VS_OUTPUT Input) : COLOR0
   {
      float2 pxSz = float2(1.0 / tWidth,1.0 / tHeight);
      float4 outC = 0;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,-4.0 * pxSz.y * blurSize)) * 0.05;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,-3.0 * pxSz.y * blurSize)) * 0.09;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,-2.0 * pxSz.y * blurSize)) * 0.12;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,-pxSz.y * blurSize)) * 0.15;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,0)) * 0.16;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,pxSz.y * blurSize)) * 0.15;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,2.0 * pxSz.y * blurSize)) * 0.12;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,3.0 * pxSz.y * blurSize)) * 0.09;
      outC += Input.Color * tex2D(s, Input.TexCoord.xy + float2(0,4.0 * pxSz.y * blurSize)) * 0.05;
      outC.r = 0;
      outC.g = 0;
      outC.b = 0;
      outC.a *= 0.8;
      return outC;
   }

```

When the blur size is \< 5, it looks like Photoshop's, but when I bring it up to make drop shadows, it starts looking like this:

Top is my game, bottom is photoshop. Notice the lines that form on mine. I think it stems from reaching the edge of the texture maybe. What could I do to make it look more like Photoshop's?

Thanks

# Answer
> 7 votes
When blurSize gets too large, the texture samples will be spaced so far apart from each other that some pixels that should be in the blur will be missed. This can easily lead to aliasing. To do really large blurs you would have to sample a lot more pixels, but since that's slow (and/or impossible depending on the limit for texture samples on your GPU), you could repeat the blur several times, or you could downsample the image to a smaller size, blur it, and then upsample with bilinear filtering. Either approach will yield a good approximation of a large blur radius.

---
Tags: c++, shaders, hlsl
---


# Question
Title: Is it possible to access vertex values of an object created using display lists?
I wanted to learn to develop games so started with tetris. I encountered a problem right in the beginning. My game is 20% ready. There are five types of shapes viz YELL, BOX, LINE, TEE, YEL which are shapes of different kinds. I created five display lists like this

```
#define YELL 1
#define BOX 2
#define LINE 3
#define TEE 4
#define YEL 5
int bs=20;
void defineshapes()
{
glNewList(YELL,GL_COMPILE);
    glPushMatrix();
    glTranslated(-bs,0,0);
    glColor3fv(color[color1]);
    glBegin(GL_POLYGON);
    glVertex2i(0,0);
    glVertex2i(bs,0);
    glVertex2i(bs,-bs);
    glVertex2i(0,-bs);
    glEnd();
    glTranslated(bs,0,0);
    glColor3fv(color[color2]);
    glBegin(GL_POLYGON);
    glVertex2i(0,0);
    glVertex2i(bs,0);
    glVertex2i(bs,-bs);
    glVertex2i(0,-bs);
    glEnd();
    glTranslated(bs,0,0);
    glColor3fv(color[color3]);
    glBegin(GL_POLYGON);
    glVertex2i(0,0);
    glVertex2i(bs,0);
    glVertex2i(bs,-bs);
    glVertex2i(0,-bs);
    glEnd();
    glTranslated(-2*bs,-bs,0);
    glColor3fv(color[color4]);
    glBegin(GL_POLYGON);
    glVertex2i(0,0);
    glVertex2i(bs,0);
    glVertex2i(bs,-bs);
    glVertex2i(0,-bs);
    glEnd();
    glPopMatrix();
glEndList();
glNewList(BOX,GL_COMPILE);
    glPushMatrix();
      .....

```

and randomly picking one like this

```
srand(time(NULL));
color1=rand()%6;
color2=rand()%6;
color3=rand()%6;
color4=rand()%6;
defineshapes();
randshape=rand()%5+1;

```

and drawing in display function like this

```
void display()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glTranslated(x2,y2,0);
    glCallList(randshape);
    glPopMatrix();
    glFlush();
}

```

I expected problem in the beginning itself when i used the display lists because i had to access the vertex values(x,y) of the shapes to check if they might overlap with another block below before moving them down. Is there a way of knowing the vertex values of objects drawn using display lists.

I encountered the same problem once before when i needed to create a tyre of a car. I wanted the tyre to be painted with colors so created a mesh by rotating a circle again using display lists. Then i needed to know the values of the intersection points of longitudes and latitudes which i didnt know how to get so i abandoned that task.

A YELL looks like this

What is the easiest method of getting around this problem. I am sure OpenGL has a way of getting this done but i am new to it.

# Answer
> 2 votes
No, there's no way to look at the vertex data inside a display list. Even using more modern technology like VBOs or whatever, while you can look at the vertex data after you set it up, it's not necessarily a good idea to do so (it could cause performance problems if you try to look at the data while the GPU is using it).

In any case, it's not necessary. Just keep your own copy of the data in your own structures and you can look at it whenever you want. In fact, for collision detection for Tetris you don't even really want vertex data; it's much simpler if you just keep track of which grid squares are occupied or not.

---
Tags: opengl, collision-detection
---


# Question
Title: Rotation matrix derived from quaternion is opposite of expected direction
When I calculate a rotation matrix from a quaternion, it seems to be in the opposite direction. For instance:

For a rotation of +45 degrees about the Y-axis, I would expect to get the following matrix:

```
# Pesudo Code
m1 = Matrix()
m1.RotateEulerY(45)
m1 =
| 0.71  0.00 0.71 0.00  |
| 0.00  1.00 0.00 0.00  |
| -0.71 0.00 0.71 0.00  |
| 0.00  0.00 0.00 1.00  |

```

However the rotation matrix calculated from a quaternion with the same rotation is

```
# Pesudo Code
axis_angle = AxisAngle((0,1,0), 45)
quat = Quaternion(axis_angle)
quat = { 0.0,0.375,0.0,0.927 }

rotate_matrix = quat.ToRotationMatrix()
rotate_matrix =
| 0.72 0.00 -0.69 0.00 |
| 0.00 1.00 0.00  0.00 |
| 0.69 0.00 0.72  0.00 |
| 0.00 0.00 0.00  1.00 |

```

Which happens to be a rotation of -45 about the Y-axis. I have tried to get the rotation matrix from the angle axis and it the same as the expected result.

Is this the expected behaviour or have I made a mistake/assumption somewhere? (Yes, the answers are not exactly the same; for now I am assuming it is a rounding error since the answers are so close).

Background info: I am using column major matrix, i.e. OpenGL style. The algorithms used to calculate the rotation matrix from the quaternion comes from http://www.j3d.org/matrix\_faq/matrfaq\_latest.html, Q54.

**UPDATE #1**

As teodron suggested, , I have tried to do a Quaternion(q) to Rotation Matrix(M) and back to Quaternion combination (i.e. q-\>M-\>q'). I also did a M-\>q-\>M' conversion for sanity check.

While q == q' and M == M', the conversion between q and M is wrong!

The rotation used in the example is the same as before, a rotation of +45 around the Y-axis. The matrix is right hand orientated, using column major vector, a.k.a openGL conformance. Matrix and Quaternion format is shown below:

```
#       | 0 4 8  12 |
# M =   | 1 5 9  13 |
#       | 2 6 10 14 |
#       | 3 7 11 15 |
#
# q =   {i,j,k,w}

```

First convert M to q then back to q.

```
#M->q->M'

# I am confident M is the correct representation for the rotation.
M =
| 0.71 0.00 0.71 0.00 |
| 0.00 1.00 0.00 0.00 |
| -0.71 0.00 0.71 0.00 |
| 0.00 0.00 0.00 1.00 |

# Here I would expect the quaternion to be all positive, but the
# j component is negative!

q =
{ 0.00, -0.38,0.00, 0.92}

# M' == M
M' =
| 0.71 0.00 0.71 0.00 |
| -0.00 1.00 0.00 0.00 |
| -0.71 -0.00 0.71 0.00 |
| 0.00 0.00 0.00 1.00 |

```

second part: from q to M to q'

```
#q->M->q'

# I have created the quaternion from both an axis angle and euler angle
# and both approaches give me the same answer
q =
{ 0.00, 0.37,0.00, 0.93}

# Here M is different from the Matrix in the first part
M =
| 0.72 0.00 -0.69 0.00 |
| 0.00 1.00 0.00 0.00 |
| 0.69 0.00 0.72 0.00 |
| 0.00 0.00 0.00 1.00 |

# but q' == q!
q' =
{ 0.00, 0.37,0.00, 0.93}

```

Since the q\<-\>M is consistently wrong, I thought I would focus on q-\>M for now.

I had check the formula to convert a quaternion to matrix across different sources and they are all consistent with one another. Basically the normal maths style, row-major matrix is as follows: (taken from http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/index.htm)

```
| 1 - 2(kk + jj)    2(ij - kw)       2(jw + ik)    |
| 2(ij + kw)        1 - 2(ii + kk)   2(jk - iw)    |
| 2(ik - jw)        2(jk + iw)       1- 2(jj + ii) |

```

Hence the openGL column major matrix equivalent should be

```
| 1 - 2(kk + jj)    2(ij + kw)      2(ik - jw)      |
| 2(ij - kw)        1 - 2(ii + kk)  2(jk + iw)      |
| 2(jw + ik)        2(jk - iw)      1- 2(jj + ii)   |

```

Comparing this with the column major rotation matrix as generated via a rotation of angle A around Y axis.

```
| cos(A)    0   sinA    |
| 0         1   0       |
| -sinA     0   cosA    |

```

Now the problem is more obvious to me: Looking at M\[2\] for both matrices, the quaternion matrix ,(2(jw + ik)), will produce a positive while the rotation matrix, -sinA, will produce a negative value!

I am at a loss here; I cannot think of a reason why these two matrices differ and I don't know what should I investigate next.Any ideas?

UPDATE #2

This is an update to explain the solution to the problem. Basically it boils down to how I ordered the elements in the matrices. For my case I did not need to transpose the original quaternion to matrix formula; some websites do perform the transpose because they have ordered it differently.

# Answer
> 3 votes
You're getting the transpose of the matrix you wanted, so you probably just have a row-vector vs. column-vector issue; that is, you're using row vectors and the source where you found the quat-to-matrix conversion formula was using column vectors, or vice versa.

# Answer
> 0 votes
Quaternions, when converting to rotation matrices, can be treated as either left-handed or right handed. One rotates in one direction, and obviously the other in the opposite direction. If you mix formulas from different sources you will often find the results don't always line up -- though one would hope if using only equations from one source it'd be consistent.

So in short, this is a typical issue that arises. It is a matter of interpretation and neither result is more correct, just perhaps not consistent in your system. Either take the time to make all your formulas line up (which is often non-trivial), or simply negate the angle if you want something quick.

---
Tags: rotation, quaternion
---


# Question
Title: Java game design question (graphical objects)
I'm beginner in game development, in Java and here on this site too and I have a game design question. Please comment my idea:

I have a main loop which call update and draw method. I want to use an ArrayList which stores graphical objects, they have coordinate and image or text to draw and my game objects extends this class. In update, I can choose which objects should be put in the array and in draw method I'll display the elements of array on the screen. I'm using a buffer and draw first there. Here is a simple (not full) code, only the logic:

```
public class GamePanel extends JPanel implements KeyListener
{
   ArrayList<graphicalObjects> graphArray = new ArrayList<graphicalObjects>();

   public void update()
   {
      //change the game scene, update the graphArray, process input etc.
   }

   public void draw()
   {
      //draws every element of graphArray to a JPanel
   }

   public static main(String[] args)
   {
      while(true)
      {
          update();
          draw();
      }
   }
}

```

My questions:

1. Should have I use interface or abstract class for graphicalObjects? graphicalObjects class and the ArrayList really needs or there is some better solution?
2. How to draw objects? They draw themself with their own method or in the draw method I have to draw manually based on graphicalObjects variables (x,y coordinates, image etc.)?
3. If this conception is wrong, please suggest another one!

# Answer
> 1. **Should have I use interface or abstract class for graphicalObjects? graphicalObjects class and the ArrayList really needs or there is some better solution?**

I would go with an interface. If all graphical objects have lots of similar data, you may reconsider.

> **2. How to draw objects? They draw themself with their own method or in the draw method I have to draw manually based on graphicalObjects variables (x,y coordinates, image etc.)?**

I suggest you follow Javas pattern and pass on a `Graphics` object and let the object paint themselves. Just set clip and offset properly before you pass on the graphics object.

> **3. If this conception is wrong, please suggest another one!**

I think it's okay, but here is a small remark:

Most Java UI's are event-driven. Since you seem to plan to implement a KeyListener, I would suggest you follow this convention. That is, throw out the update/draw loop, and repaint the panel after processing received events.
> 7 votes

# Answer
## What needs an object to be drawn

Let's start with a basic class for an object which should do the following.

* `The coordinates` Simple variables such as `x_pos` and `y_pos`
* `An Image` The face of the object
* `a render() method` To draw the object

## The coordinates

Every object requires the coordinates to note it's position on the screen. They can be complex `Vectors` and also `simple vars`. Let's name them `x_pos` and `y_pos`. They need to set in the constructor for games (To have multiple instances).

## The image

An image let's the user to identify the game objects. Loading images is extremely easy than sounds. Here's a `loadImage() method`.

```
public static Image loadImage(String name){
    Image img = null;
    if (cache.containsKey(name)) {
        img = cache.get(name);
    } else {
        try {
            img = new ImageIcon(this.getClass().getClassLoader().getResource(name)).getImage();
            cache.put(name, img);
        } catch (Exception e) {
            System.err.println("Error loading image : " + name
                    + "\nFatal error. The program is exiting.");
        }
    }
    return img;
}

```

Here the cache is a `HashMap` so that an image is only loaded once and all the instances use the same image.

## A `render()` method

In this method you would draw the object to the game. See it and you may understand it without any explanation.

```
public void render(Graphics2D g){
    g.drawImage(img, x_pos, y_pos, null);
}

```

Where the `null` refers to `ImageObserver` class which we do not need. To draw the object, simply call this method from the `paint` method of the game. `(Don't forget to cast the legacy Graphics class to the new Graphics2D class)`.

## Reference

You may see this class as a reference. Just rename it to `graphicalObjects` and use it up.

GObject class

List of pre-created actions (useful for beginners) like bounce() etc.,

Pre-Created Actions (Inspired by Game Maker)
> 0 votes

---
Tags: architecture, java
---


# Question
Title: Is it safe to cast my 2D points to 3D points for a library which only takes Vector3s?
I need to cast a ray in 2D space for bullet collision detection, but the Ray.Intersects method requires a BoundingBox which uses vector3's not vector2's. My question is should I just ignore the Z value and pretend it's a vector2? Raycasting is already slow enough so I think having calculations done in an unnecessary 3rd deminsion should be eliminated even if the value is just 0, but I don't know.

So should I implement my own raycasting system maybe using Bresenham's line algorithm which is for 2 dimensions or should I go the cheap way and make a bounding box a bounding plane?

# Answer
Yes, you can just use Vector3's where the z-value is 0.

In geometry, any 2D point also exists in the 3rd dimension. In a 2D game, everything could be represented with Vector3s where the z-values are all identical. Often in a 2D game, you use the Z value as the *depth*, to draw a tree in the background (low Z value) or the main character in the foreground (higher Z value).
> 0 votes

---
Tags: xna, vector, raycasting, linear-algebra
---


title: Where can I find indie "teams"

text:
# Question
Title: Where can I find indie "teams"
I'm looking to work over the internet in a team of people to make a game. I'm not looking to make a profit, I just want the experiance. Where can I find similary minded persons?

# Answer
> 7 votes
Personally I don't like working with random people over the internet. Also you will find few games actually succeed without the dynamic of loyalty and accountability that comes with actually having to deal with someone.

If you are a student ask around, I promise there are others interested in the same things as you. If not Google around and try to find a game development meet up in your area. Also there are often groups dedicated to certain technologies (XNA, Unity) if you live in a populate enough area.

If that fails I suggest looking at currently under development opensource games and seeing if they will let you join. Forking it and making a meaning full improvement or fix is a great way to get a team to enthusiastically welcome you.

But just speaking from experience, its near impossible to get any sort of dedication or staying power for a project unless the members and invested in it and each other emotionally.

Anyways that is my 2c. Mostly coming from experience founding modding teams.

# Answer
> 3 votes
IndieDB is a good place for indie develoers. They even have a dedicated job section. Paid and unpaid.

For beginners, its easier to start with modding, ModDB. Pick a game your like to mod. Then look for existing mods and see if they need someone of your skill. i.e. Half Life 2.

Also, note what @ClassicThunder said. You said you only want the experience. So, for *ONLY* experience both of them are a very good place to start. But, very few of them actually get completed. So, prepare for anything!

# Answer
> 2 votes
I highly recommend going to game jams, where people attempt to make video games in a short time span. If you are looking for experience in working with others, they are great environments to do so.

I recommend the Global Game Jam, but there are many others. A place to look for them is CompoHub which is mainly online game jams/contests but also lists local ones as well. Some places have much more of a game development scene than others.

---
Tags: project-management
---


# Question
Title: How would I write a shader that supports 2 different texture coordinates?
Hi I am not very good with writing shaders. How would I make a shader that simply supports 2 texture coordinates so I can load up 2 different textures to be used at the same time but on different parts of my world? Right now I have 1 texturecoord variable setup and I load a texture through it using GraphicsDevice-\>SetTexture(0, &Texture); and making sure my VertexDeclaration and FVF both support that, but how can I add a second texture to this? Would I make it so that I make separate coordinates and link the coordinates to a texture? How would I write that?

# Answer
render code:

```
GraphicsDevice->SetTexture(0, &Texture);
GraphicsDevice->SetTexture(1, &SecondTexture);

```

hlsl declaration:

```
sampler Texture0 : register(s0);
sampler Texture1 : register(s1);

```

Use the vertices's other coordinates to sample Texture1.
> 1 votes

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


title: How to precisely limit fps

text:
# Question
Title: How to precisely limit fps
I am having trouble making my game's main loop to run at *exactly* N fps. Let's say i want game to run at constant 60 fps. Here is part of my code:

```
int ticksPerSecond = 60;
int skipTicks = 1000 / ticksPerSecond;
int maxFrameskip = 10;

// ...

while(true)
{
    loops = 0;
    while (Environment.TickCount > nextGameTick && loops < maxFrameskip)
    {
        OnUpdate();
        nextGameTick += skipTicks;
        loops++;
    }

    Render();
}

```

As a result i am getting around 64 fps, not 60. Why is that and what am i doing wrong here?

# Answer
You will have a rounding error.

```
(int)(1000 / 60) = 16
1000 tickspersecond / 16 ticksperframe = 62.5 framespersecond
// forgive my horrible units

```

Also, it looks like you abort your loop when you hit 10 updates. Is your update so fast that that ever happens?
> 2 votes

---
Tags: game-loop
---


title: How to render depthmap image in 3d?

text:
# Question
Title: How to render depthmap image in 3d?
I'm new to game development and XNA. I have this depthmap image and I want to render it in 3D, how do I do it, any tutorial or blog post would be helpful.

# Answer
> 1 votes
Load a texture:

```
texture = Content.Load<Texture2D>("depthmapimage");

```

Put the texture data into a color array:

```
Color[] pixels = new Color[width * height];
texture.GetData(0, new Rectangle(), pixels, 0, width * height);

```

Iterate the array to generate vertices:

```
for (i = 0; i < height; i++){
    for (j = 0; j < width; j++) {
        // check red value for z, convert i and j into x and y, etc...
        nextvertex = generateVertexFromColorDatum(pixels[i * width + j]);
        listOfVertices.Add(nextvertex);
    }
}

```

Follow this article to draw them:

http://msdn.microsoft.com/en-us/library/bb196414.aspx

Or examine this tutorial project:

http://xbox.create.msdn.com/en-US/education/catalog/sample/primitives\_3d

# Answer
> 0 votes
For a simple vizualisation you can create plane mesh tessalated in you depth buffer resolution (for example 1024x728 vertices). If the plane is in xz axis, move vertices in y axis based on values in depth buffer. You can also use near and far plane information to have correct depth range and if you use perspective camera, you should take into account FoV angle too.

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


# Question
Title: Menu selection wont stay on selected option
My Menu has a START and a QUIT option. I'm using a controller's D-PAD for selection. The game begins with START highlighted. When I push the down button on the D-PAD, it highlights the QUIT option. Problem is when I release the down button, it returns to highlighting START.

Is there a way to possibly hold the position so that if I highlight QUIT, it will stay highlighted after releasing the button?

```
//First starts with START highlighted:

if(menuSelect == 1 && GC.getDPADDir() == 7){ // if QUIT is highlighted, push up
        menuSelect++;
    }
    else if(GC.isButtonPressed(1)){
        // go to game
        sbg.enterState(1);
    }

if(menuSelect == 2 && GC.getDPADDir() == 1){ // if start is highlighted, push down
        menuSelect--;
    }
    else if(GC.isButtonPressed(1)){
        // quit
        System.exit(0);
    }

```

# Answer
Not exactly what you are looking for but perhaps you could try it like so:

```
private int maxMenuItems  = 2;
private int menuSelect  = 1;

```

-Check for direction first

```
if(GC.getDPADDir() == 7){
        menuSelect++;
        if(menuSelect > maxMenuItems) menuSelect  = maxMenuItems;
    }
else if(GC.getDPADDir() == 1){
        menuSelect--;
        if(menuSelect < 1) menuSelect = 1;
    }

```

-Then loop over the button press check

```
if(GC.isButtonPressed(1)){
   switch(menuSelect){
       case 1:
       sbg.enterState(1);
       break;
       case 2:
       System.exit(0);
       break;
   }
}

```

I havn't done much with menus and what not. But I think your flaw is within your if else "cluster". It would also be easier to use a base of 0. You might want to iterate over your items or reference them by index if you were to put them in an array.
> 2 votes

---
Tags: java, lwjgl, slick, controllers
---


# Question
Title: How do I create a third Person View using DXUTCamera in DX10?
I am creating a 3d flying game and using DXUTCamera for my view.

I can get the camera to take on the characters position, But I would like to view my character in the 3rd person.

Here is my code for **first person view**:

```
    //Put the camera on the object.

    D3DXVECTOR3 viewerPos;
    D3DXVECTOR3 lookAtThis;
    D3DXVECTOR3 up         ( 5.0f, 1.0f, 0.0f );
    D3DXVECTOR3 newUp;
    D3DXMATRIX matView;

    //Set the viewer's position to the position of the thing.

    viewerPos.x = character->x;   viewerPos.y = character->y;
    viewerPos.z = character->z;

    // Create a new vector for the direction for the viewer to look

    character->setUpWorldMatrix();
    D3DXVECTOR3 newDir, lookAtPoint;
    D3DXVec3TransformCoord(&newDir, &character->initVecDir,
                                  &character->matAllRotations);

    // set lookatpoint

    D3DXVec3Normalize(&lookAtPoint, &newDir);
    lookAtPoint.x += viewerPos.x;
    lookAtPoint.y += viewerPos.y;
    lookAtPoint.z += viewerPos.z;

    g_Camera.SetViewParams(&viewerPos, &lookAtPoint);

```

So does anyone have an ideas how I can move the camera to the third person view? preferably timed so there is a smooth action in the camera movement. (I'm hoping I can just edit this code instead of bringing in another camera class)

# Answer
> 1 votes
For those of you wanting code. Here's my solution

LookAtPoint is my static view position, and then I simply transform the coords to that of the objects world.

```
        D3DXVECTOR3 viewerPos;

        viewerPos.x = character->x;   viewerPos.y = character->y;
        viewerPos.z = character->z;

                D3DXVECTOR3 newDir, newDirNorm, lookAtPoint( 0.0f, 1.0f, 5.0f  );
                D3DXVec3TransformCoord(&newDir, &lookAtPoint,
                    &character->matWorld);

    D3DXVec3Normalize(&newDirNorm, &newDir);

    D3DXVECTOR3             vecEye = newDir;
    D3DXVECTOR3             vecAt = viewerPos;

    g_Camera.SetViewParams ( &vecEye, &vecAt);

   // g_Camera.SetProjParams(D3DXToRadian (60.0f), 5.5, 0.5f, 100.0f);

    // Set the Camera parameters
    g_Camera.SetProjParams ( D3DX_PI/4, 5.5, 30.0f, 30.0f);
    g_Camera.SetResetCursorAfterMove ( true);

    g_Camera.FrameMove(fElapsedTime);

```

# Answer
> 0 votes
You can see third person camera implemented in MultiAnimation sample in DirectX SDK (June 2010):

NOTE:

It is static attached first person camera (static relative to person), not good for person, but sufficient for airplane plane.

Anyway, DXUT is full of bugs (reading uninitialised variables, for example), (i think) it is sufficient just for SDK samples, or rewrite it to stl compliant and run through static code analysis.

It is better to use XNAMath / DirectxMath instead (deprecated) D3DXMath.

---
Tags: c++, directx10
---


# Question
Title: Correct use of VAO's in OpenGL ES2 for iOS?
I'm migrating to OpenGL ES2 for one of my iOS projects, and I'm having trouble to get any geometry to render successfully. Here's where I'm setting up the VAO rendering:

```
void bindVAO(int vertexCount, struct Vertex* vertexData, GLushort* indexData, GLuint* vaoId, GLuint* indexId){

//generate the VAO & bind
glGenVertexArraysOES(1, vaoId);
glBindVertexArrayOES(*vaoId);

GLuint positionBufferId;

//generate the VBO & bind
glGenBuffers(1, &positionBufferId);
glBindBuffer(GL_ARRAY_BUFFER, positionBufferId);

//populate the buffer data
glBufferData(GL_ARRAY_BUFFER, vertexCount, vertexData, GL_STATIC_DRAW);

//size of verte position
GLsizei posTypeSize = sizeof(kPositionVertexType);

glVertexAttribPointer(kVertexPositionAttributeLocation, kVertexSize, kPositionVertexTypeEnum, GL_FALSE, sizeof(struct Vertex),  (void*)offsetof(struct Vertex, position));
glEnableVertexAttribArray(kVertexPositionAttributeLocation);

//create & bind index information
glGenBuffers(1, indexId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *indexId);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vertexCount, indexData, GL_STATIC_DRAW);

//restore default state
glBindVertexArrayOES(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}

```

And here's the rendering step:

```
//bind the frame buffer for drawing
glBindFramebuffer(GL_FRAMEBUFFER, outputFrameBuffer);

glClear(GL_COLOR_BUFFER_BIT);

//use the shader program
glUseProgram(program);

glClearColor(0.4, 0.5, 0.6, 0.5);

float aspect = fabsf(320.0 / 480.0);
GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f);

GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -1.0f);

GLKMatrix4 mvpMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix);

//glUniformMatrix4fv(projectionMatrixUniformLocation, 1, GL_FALSE, projectionMatrix.m);
glUniformMatrix4fv(modelViewMatrixUniformLocation, 1, GL_FALSE, mvpMatrix.m);

glBindVertexArrayOES(vaoId);
glDrawElements(GL_TRIANGLE_FAN, kVertexCount, GL_FLOAT, &indexId);

//bind the color buffer
glBindRenderbuffer(GL_RENDERBUFFER, colorRenderBuffer);
[context presentRenderbuffer:GL_RENDERBUFFER];

```

The screen is rendering the color passed to glClearColor correctly, but not the shape passed into bindVAO. Is my VAO being built correctly? Thanks!

# Answer
So it turns out there were two issues. In this line:

```
glBufferData(GL_ARRAY_BUFFER, vertexCount, vertexData, GL_STATIC_DRAW);

```

I was using the vertex count instead of the size of the buffer in bytes. It should have been:

```
glBufferData(GL_ARRAY_BUFFER, vertexCount*sizeof(GLfloat), vertexData, GL_STATIC_DRAW);

```

Then in the rendering step, I was passing the vertex data type instead of the index data type into glDrawElements here:

```
glDrawElements(GL_TRIANGLE_FAN, kVertexCount, GL_FLOAT, &indexId);

```
> 2 votes

---
Tags: opengl, graphics, iphone, ios, rendering
---


# Question
Title: GraphicsAdapter lacks a definition for CheckDeviceMultiSampleType
The MSDN is really confusing about this, with all their different versions of XNA jumbled together for my google results. All I want to do is find out, in XNA 4.0, what antialiasing modes are supported by the display adapter. Supposedly, this involves calling GraphicsAdapter.CheckDeviceMultiSampleType(), but that function isn't defined. What should I be using in its place?

# Answer
That method was removed in XNA4 since it was no longer needed since we now have the reach and hi-def profiles. You can now just prefer multisampling or not and the framework will set an appropriate `MultiSampleCount` if possible. You can still set this value yourself here but setting it too high won't cause an error.

http://msdn.microsoft.com/en-us/library/bb976069.aspx

> In XNA Game Studio 3.1, use GraphicsAdapter.CheckDeviceMultiSampleType to query the hardware for multisample support. In XNA Game Studio 4.0 Refresh, set the PreferMultiSampling property on the GraphicsDeviceManager class to true to enable multisampling for the back buffer. This will be ignored if the hardware does not support multisampling.

Btw if you have problems with MSDN. In the top left of the current article you're viewing you can select the proper version (if available).
> 3 votes

---
Tags: xna, graphics, antialiasing
---


title: Should I render with mipmaps?

text:
# Question
Title: Should I render with mipmaps?
The game I'm working on is very simple. It's a top down scroller. The camera never moves in any way, and all of the objects are in the same location on the Z axis. Since it's a bullet hell game, there are a lot of models on the screen at any given time. That being said, when I call RenderTarget2D, should I set mipmaps to true or false? I haven't noticed any difference at all so far either way.

# Answer
> 6 votes
I think you're confusing a couple of things here.

First mipmapping: mipmapping is a technique where if an object is small on the screen a small texture is used instead of the a bigger texture. This reduces texture bandwidth usage by just loading a texture that is big enough, instead of loading one very big texture. And it alleviates certain aliasing problems. See this wiki page.

Now if you construct a RenderTarget2D with mipmaps then the RenderTarget, which is also a Texture will have mipmaps. This means that the resulting image on the render target will have a full mipmap chain, not that the objects rendered to the render target will be mipmapped. Setting mipmaps to true on rendertargets is only useful if you are going to display the resulting texture and different sizes.

So the short answer is: **no** :)

---
Tags: xna, graphics
---


# Question
Title: Finding out what pixel on the screen the fragment falls on
In my 2D game, I render tiles. I want to do lighting without needing an extra buffer the size of the screen.

Either in glsl or hlsl, what could I feed to the shader each time I render a bitmap so that it knows what pixel on the scren it will fall on. That way I can do per pixel lighting.

Currently I only get the UV coord relative to the texture, not the screen.

Thanks

Using ps 2.0

# Answer
> 5 votes
If it's ps3+, use vPos in assembly or VPOS/SV\_POSITION in HLSL.

If you don't want to use ps3+, then you need to pass, in another texcoord, the position before it gets mangled into clipspace.

e.g.

```
struct output{
   float4 Position : SV_POSITION;
   float4 Fake_Position : TEXCOORD0;
}
VShader(youstruct input)
{
    a = input.Position * World
    b = a * View;
    c = b * Projection;

    output.Position = c;
    output.fake_Position = b;
}

```

# Answer
> 2 votes
In HLSL you can use VPOS or SV\_Position to get the screen space position in the pixel shader.

# Answer
> 2 votes
In the vertex shader, you could augment the output so that it contains a texture coordinate. That coordinate should be the vertex's world position, projected into screen space by world and project matrices. This would be identical to what the rasterizer does for its own purposes, except you can use it in your pixel shader.

---
Tags: c++, shaders, glsl, hlsl
---


# Question
Title: How do I use screen-space derivatives to antialias a parametric shape in a pixel shader?
In Valve's Alpha Tested Magnification paper, it mentions using "per-pixel screen-space derivatives" for doing anti-aliasing. My understanding is that this is the `ddx` and `ddy` intrinsic functions in HLSL?

I'm trying to draw parametric shapes (for example a circle: **x² + y² \< 1**) in a shader, and I don't know how to use this technique to correctly anti-alias the edge pixels of my shape. Can someone provide an example?

For completeness, here is an example of the kind of pixel shader I'm making:

```
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float dist = input.TexCoord.x * input.TexCoord.x
               + input.TexCoord.y * input.TexCoord.y;
    if(dist < 1)
        return float4(0, 0, 0, 1);
    else
        return float4(1, 1, 1, 1);
}

```

# Answer
Taking your example, you have a step function of the distance, which produces a perfectly hard (aliased) edge. A simple way to antialias the circle would be to turn that into a soft threshold, like:

```
float distFromEdge = 1.0 - dist;  // positive when inside the circle
float thresholdWidth = 0.01;  // a constant you'd tune to get the right level of softness
float antialiasedCircle = saturate((distFromEdge / thresholdWidth) + 0.5);
return lerp(outsideColor, insideColor, antialiasedCircle);

```

Here I used a clamped linear ramp for a soft threshold function, but you could also use `smoothstep` or something else. The `+ 0.5` is to center the ramp on the mathematical location of the edge. Anyway, the point is that this function smoothly changes from `outsideColor` to `insideColor` over some range of distances, so if you pick `thresholdWidth` appropriately you'll get an antialiased-looking edge.

But how should you choose `thresholdWidth`? If it's too small, you'll get aliasing again, and if it's too large the edge will be overly blurry. Moreover, it'll generally depend on camera position: if `dist` is measured in world-space or texture-space units, then a `thresholdWidth` that works for one camera position will be wrong for another.

Here's where the screen-space derivatives come in (yes, they're the `ddx` and `ddy` functions as you guessed). By calculating the length of the gradient of `dist` you can get an idea how rapidly it's changing in screen space and use that to estimate the `thresholdWidth`, like:

```
float derivX = ddx(distFromEdge);
float derivY = ddy(distFromEdge);
float gradientLength = length(float2(derivX, derivY));
float thresholdWidth = 2.0 * gradientLength;  // the 2.0 is a constant you can tune

```

You still have a value you can tune to get the desired level of softness, but now you should get consistent results regardless of camera position.
> 11 votes

---
Tags: hlsl, fragment-shader, antialiasing
---


title: Raycasting Collision Detection

text:
# Question
Title: Raycasting Collision Detection
I need to check for collisions when firing a bullet, but I have a few questions first. My game is 2D and tile based, it also uses the XNA framework. From what I've read raycasting or continuous collision detection is the way to go for high speed bullets. XNA has a method called Ray.Intersects which takes a bounding box, does this mean that I should be starting at a point and looping through all the tiles in a line to see which tile intersects like this?

Now that example required 10 checks and now I have the information I need to know where the collision is exactly, but wait what if a person jumps in line of the ray? Well now I need to be performing these checks every frame in order to determine if a player comes in line. Assuming my game has a solid 60 FPS I'm now up to 60 checks every second or 10 checks a frame. Maybe I've shot my weapon 5 times and the wall is 50 blocks away, that would be a lot of checks.

So if you couldn't figure out what I'm getting at here these are my questions.

* In order to preform raycast collisions do I start at a point (barrel of weapon) and loop through all the tiles asking "does the ray hit this tile?" until I've hit something (a wall)?
* How do I optimize it or does it even need optimizing?

Remember the system needs to...

* be able to obtain all the necessary information such as where does the collision take place exactly?
* account for players or obstructions getting in the path of the ray.

# Answer
Assuming you've benchmarked this and are sure this is a bottleneck keep reading. If not stop. Don't worry and be happy :).

It's true that you will need to run the collision check algorithm every time you fire a bullet. And depending on how long it takes the bullet/laser to disappear you will have to do it multiple frames. However when you implement a solid spatial partitioning algorithm the number of candidates that can intersect the ray are few.

One of the most well know implementations is the quad tree. Basically it's a data structure that let's you ask quickly in what tile the starting point of your ray is. It also enables you to quickly look up adjacent tiles and it will allow you to ignore most of your tiles. It will also tell you quickly what other objects are on the inspected tile. Also don't forget the following optimization: if you start from the bullet source and keep checking from there you can stop as soon as you've detected a hit.

Note I also found this neat tutorial, it's a bit dated but it might get the idea across, it will especially show that one tile in a quad could, and probably should, hold multiple 'world' tiles. http://www.heroicvirtuecreations.com/QuadTree.html
> 5 votes

---
Tags: collision-detection, raycasting, linear-algebra
---


title: Variable Visibility Class Interaction

text:
# Question
Title: Variable Visibility Class Interaction
I have a very general question about how game classes interact with eachother in a growing RPG game project I'm working on. (Writing it in java/Slick2D, not that is matters because the question is about the concepts)

I have a lot of classes, to name a few, a game class that stores the main game loop that updates all the objects and other classes like player, enemy, HUD, etc. Some variables (mostly ones from Player) are needed in other classes. For example, I need to get the player name, level, xp many times in other classes; my HUD needs the player info to display, I have a class to execute ingame cheat commands such as giving player xp, and my Inventory HUD needs to get the players inventory items to show, etc.

To summarize, what are some general pointers when it comes to getting variables from other classes. Lets say playerXP: my World class declares and holds a Player class, but there are so many other classes, unrelated to the player but still need to get player information. I don't want to make the playerXP public because then some class might accidentally change it. I just need to be able to access player info from many other classes.

# Answer
The temptation is to make the Character object globally accessible in some way or another. (The Singleton pattern and the Registry pattern come to mind.) Do not follow that temptation.

Instead, pass the Character object explicitly to whatever other objects and methods need it. Make the character stats private, but provide public getter methods that just return properties. That way, other components can read the properties but not change them.

Have a look at http://www.youtube.com/watch?v=-FRm3VPhseI for some background on why this design is better.
> 2 votes

---
Tags: java, rpg, slick
---


title: Highlight edge on 3d cube in directx

text:
# Question
Title: Highlight edge on 3d cube in directx
I want to make a 3d editor in DX9/XNA for a project I'm working on. I'm just thinking through how I would go about certain tasks and I'm stuck on one particular thing, which is crucial to making the editor working.

The editor will allow 3d objects to be added to the scene. For example I would add a cube to the scene. Now I want to be able to select one edge of the cube. When this edge is selected it should change colour. The remaining edges should not change colour.

If my description is not clear enough then it would basically be the same as the edge tool in blender. If you look at the following image you will see the first double cube has its centre edge highlighted

http://wiki.blender.org/index.php/File:Manual-Part-II-EdgeSpecials-EdgeSlide.png

I can't recall coming across anything in DX9 or XNA that allows edges to highlighted in this way. Would this be done in a shader perhaps?

Thanks

Edit From OP: (Can't seem to post comments so editing the original.) I had considered drawing lines but wasn't sure if it would trace the exact same path as the edge. I guess I it would be best to try this first before dismissing it. The purpose of the post was to find out if xna or dx9 had something built into it to do this sort of thing. I'm currently just in the design phase so have not implemented anything.

I would accept the answer from Roy T but I can't find the option to do so! Thanks.

# Answer
You might be over-thinking this ;).

The way you phrased your question seems to indicate that you already have the edge and the two vertices that represent this edge. If not you need to look at the `Viewport.Unproject` method to shoot a ray from the mouse pointer and then see if this (almost) intersects with an edge. Anyway once you have the two vertices that represent the edge all you have to do is this:

1. First draw your model or trianglelist/trianglestrip
2. Then draw a line between the two vertices. this will be drawn over the model and will look like highlighting, especially if you draw your line not totally opaque.

That's all there is to it.
> 4 votes

---
Tags: xna, c++, c#, 3d, directx
---


# Question
Title: Why has the industry switched from C to C++?
First of all i would like to have a real answer, i'm always trying to get more from various sources and articles, and when I read things like *C++ is slow because it has virtual functions* and because of this *C is better*, i really don't know what to say and think as an human being with a brain. So please avoid to reach this level in your answer/s.

My question is about a massive switch to C++ that was completed, more or less, with Doom 3.

The interesting thing for me is that before this milestone, most of the game engines and the games itself were written in C, just like it was since the *Quake era*. It's also interesting to note that the ID software decide to completely rewrite the codebase for the IdTech 4 in C++, a massive amount of work that honestly i can't understand without a really good list of reasons.

I'm focusing on Doom 3 because I am mainly interested in the OpenGL world and in my journey i try to stay focused on this topic, so i read a lot about this, but i think that a question like that can be render-API-agnostic without too much problems.

**Why at a certain point in time the industry switched massively to C++ ? What are the reasons for the choice that ID made ?**

The last thing that i would like to say is that the C language is much more simple to implement and provides a less number of features, because of this has much less chance to be "fragmented" in pieces unlike the C++ really often does. In simplest terms i have much more chances to find a really good C compiler rather than a good C++ compiler with all the features implemented in a good way.

For example the NDK for Android still doesn't have a good C++ support ( with the r8b release ) with all the latest and greatest features, and it's the native toolkit for the most popular mobile OS in the world!

If I had wrote my code in a modern C++ I would probably be in pain now because one of the most popular OS in the world would be off-limits for me. And like Android, many other compilers are not that great.

**I should write C++ code referring to a C++ version that is 2-3 release old ?**

# Answer
> 29 votes
C++ does everything C does. You can trivially mix C and C++ in cases where the advantages of C outweigh those of C++. This is a very intentional design decision of C++.

C++ does things that C does not. This includes easy polymorphism, but also easy compile time code generation via templates. This is really handy for things like containers, which are easily C's biggest weakness. It also allows user-defined pointer-like types (smart handles) that save lots of time, as well as user-defined primitive-like types such as vectors and matrices with operator support (also saves lots of time).

Virtual functions are slower than non-virtual functions. However, you must opt in to virtual functions, and a competent programmer does so only when they're beneficial. C programmers have function pointers and often store collections of those in struct referenced by other structs; in other words, they go through extra work to recreate the exact same thing as virtual function tables. In cases where only a single function pointer is needed and no table is required, C++ still fully allows that and is equivalent to C. With a modern compiler, C++ is only slower than C in the specific cases the programmer is opting in to a feature. Also, the virtual function overhead in practice is very small on modem CPUs. Hardware today is designed for C++'s usage patterns, and is even increasingly designed for high-level interpreted langiages' needs.

C++ exceptions historically impose a lot of overhead, making C++ slower even if you're not using them. Exceptions were a terrible thing to add to C++, if for no other reason than the immense increase on complexity involved in writing exception-safe code, and in fact some container designs are literally impossible to make exception safe. Game programmers often ignore exceptions' existence, and even disable them on the compiler. Modern compilers have zero- overhead exceptions (that is, you only pay th cost for them when you actually use them).

C is simpler to learn all the rules of. C++ is a very big, complex language. C++ allows writing higher-level code, producing easier and simpler APIs. Some people want to understand the language easier, some people want to write advanced code easier. It's a trade off between simplicity of understanding what the compiler is doing with a specific piece of code vs the simplicity of writing large complex inter-connected applications. Some folks value one far more than the other, for various reasons.

In the end, C++ is a superset of C. In my opinion, there is no such this as a *highly competent* C++ programmer who is not also a passable C programmer (though there are a lot of C++ programmers who fall below my bar who would be lost in pure C). While C++ adds facilities to insulate the programmer from much of C, non- trivial C++ code often does need to use C to get things done. This is one of the primary difference between C++ and Java and C#. There's a reason that you often see "C/C++" lumped together, after all.

My personal belief -- which is shared with most other games industry professionals I've interacted with -- is that the enhanced expressiveness and high-level programming facilities of C++ outweigh the increased complexity of the language over C, and most of the other frequent anti-C++ claims made are simply out of date with today's technology.

# Answer
> 12 votes
> Why at a certain point in time the industry switched massively to C++ ? What are the reasons for the choice that ID made ?

Id Software is *not* "the industry". They are one company. While they may be influential, they aren't everyone.

I've worked on a couple of game engines that date back to 1999, and they used C++.

The principle reasons for the adoption of C++ "around that time" are:

1. It was *standardized*. C++98 is named that because it was released as an ISO standard in 1998. Until then, there were multiple dialects of C++ with no clear idea which was "real" or "correct". Once it was standardized, and compilers started implementing the standard, game developers could rely on the actual standard.
2. Remember the old joke: A guy walks into a doctor's office and says, "It hurts when I raise my arm like this." So the doctor says, "So don't raise your arm like that."

If virtual functions are slow for your needs, C++ doesn't *force* you to use them. Everything in C++ is opt-in. You *choose* to use each particular feature. If you're in performance-critical code and you don't want virtual overhead, you don't use virtual functions. Just like if you're in performance-critical code in C, you don't use function pointers.

Indeed, this led to a lot of C++ games not being idiomatic C++ (at least, not *modern* idiomatic C++), but merely "C with classes". And this is a perfectly functional way to program C++. Hell, just being able to not have to type `typedef struct` when you create a new type is a benefit.

C++ is a big bag of features, and you can pick which ones you want.

> For example the NDK for Android still doesn't have a good C++ support ( with the r8b release ) with all the latest and greatest features, and it's the native toolkit for the most popular mobile OS in the world!

Your point being? Google barely *tolerates* people using NDK; it's clear that they want everyone to use Java. The only reason NDK exists is because there are certain important developers who simply will not use the platform without it. Thus, NDK exists to service them and their feature needs.

Yes, C++ is a bigger, more complicated specification to implement. So is Java. So is *any* language except C.

Also, what do you mean "all the latest and greatest features"? If you're talking about C++11 stuff, well, nobody fully implements that yet. The spec is *barely* a year old now. Also, I don't know if NDK support C11 either; yes, C also has "latest and greatest features" that aren't supported everywhere.

Which brings up an important point: if you want your pure-C application to compile on Visual Studio, then it needs to conform to C89, and nothing higher than that. So fragmentation with C already exists. Some platforms support only C89. Some support C99. Some support C11, to varying degrees. Etc.

If you want to use C, then *use C*. The fact that other people didn't make that choice does not mean your choice is wrong or that their choice is wrong. You don't need to justify yourself to them, and *they* don't need to justify themselves to you.

# Answer
> 7 votes
> It's also interesting to note that the ID software decide to completely rewrite the codebase for the IdTech 4 in C++, a massive amount of work that honestly i can't understand without a really good list of reasons.

It's been common for them to rewrite pretty much the whole engine for every release (at least until recently - I don't know much about the last few games), and since C++ is growing in popularity it makes sense to use that rather than stick with C. Over time fewer and fewer people are going to be competent with C.

> Why at a certain point in time the industry switched massively to C++ ?

Because it gives you lots of higher level functionality while being almost entirely backwards compatible with C code.

> What are the reasons for the choice that ID made ?

Google would have answered this for you: http://fabiensanglard.net/doom3/interviews.php

*"...half the programmers really had C++ background in the beginning. I had C and Objective-C background, and I sort of "slid into C++" by just looking at the code that the C++ guys were writing. In hindsight, I wish I had budgeted the time to thoroughly research and explore the language before just starting to use it.*

*You may still be able to tell that the renderer code was largely developed in C, then sort of skinned into C++.*

*Today, I do firmly believe that C++ is the right language for large, multi-developer projects with critical performance requirements, and Tech 5 is a lot better off for the Doom 3 experience."*

> If I had wrote my code in a modern C++ I would probably be in pain now because one of the most popular OS in the world would be off-limits for me.

1. Programmers can't see into the future. They wouldn't know that there would be a new platform with poor C++ support. Android didn't exist properly until 2009. Doom 3 was from 2004.
2. Do you think programmers who are writing cutting-edge 3D games for PCs and consoles expect their code to run on phones too? Aiming for that degree of portability is very rare and often pointless due to the massive difference in power available.

> I should write C++ code referring to a C++ version that is 2-3 release old ?

Why do you care about this? Don't get trapped chasing the newest thing. If it was good enough 5 years ago, it won't have suddenly got worse now.

# Answer
> 3 votes
Well, C++ has been out since the 80s so if a compiler doesn't support it, perhaps you should use a different compiler. And also, C++ is not really much slower than C. It really is only slower if you load it down with virtual functions and other abstractions. However, C++ is used a lot today in the non unix world because of its flexibility and newer features that C doesn't have. Writing modular code in C++ is a lot easier than doing so in C and helps you to write more portable code. Back on the subject of compilers, I don't know any compiler that doesn't support C++ (maybe not C++11 fully, but any half decent compiler should support C++).

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


# Question
Title: Where can I find affordable legal advice for game software related inquiries?
I am working on simulation middleware which is applicable for game engine implementations.

What I would like to do is to make it freely available for use for all non-commercial purposes, while at the same time imposing some percentage of royalty on revenue (above a certain threshold) that is derived from my work. Something very similar to Epic's UDK licensing model.

To facilitate the use of my software, I plan to offer binaries (static libs) for several platforms, as well as obfuscated source code which I will freely distribute, in addition to documentation of the API. I simply want to impose the restriction that if you try to make money from it, I get a cut eventually.

I'm wondering if there are online forums and such where I am likely to find people who are willing to assist me in terms of learning what sort of things I have to do to get things down on the right kinds of documents. So far a site like this seems to be the most promising.

# Answer
I was very pleased with my result from findlaw.com, http://lawyers.findlaw.com/lawyer/practice/Intellectual-Property-Law

I submitted a simple web form with a question about my situation, and this site forwarded it to a practicing lawyer in the field I selected. He responded promptly. I had chosen an option for 'offers free consult', and I did indeed receive a half-hour meeting for free.

In my case, I had been served with a takedown notice that I felt was unfounded. The lawyer completely answered my (very specific) questions about the matter. Unfortunately, even being on the right side of the law still requires more than half an hour of billable time. :) I was unwilling to pursue my case, but I would certainly contact that lawyer again.
> 1 votes

# Answer
Borrowing my answer from another question:

I have no idea how capable he is; as always, Caveat Emptor.
> 1 votes

# Answer
Gamedev.net has a forum for Business and Law: http://www.gamedev.net/forum/5-business-and-law/
> 1 votes

---
Tags: legal, licensing
---


# Question
Title: How do I match and clear sequences 3 adjacent coloured blocks?
I'm making a game with elements of a match-3 puzzler (such as *Columns*, *Bejeweled* or *Tetris Attack*). I don't know where to begin creating an efficient algorithm for matching and clearing.

My assumptions:

* Blocks of a like color can be matched horizontally, vertically, or diagonally in sets of *at least* 3.
* Blocks are held within a grid. They do not move horizontally.
* However, blocks *do* move vertically due to gravity.
* This is an action game, therefore we have to check up on the grid each frame.
* Due to the design of my game, however, we only need to check for matches if at least one block was falling in the previous frame.

Where do I go from here?

# Answer
When a block moves, add it to a list that needs checking.

When you check a block remove it from the list.

First, decide if lines of 4+ count and if not, which set of 3 takes precedence in a row of 4.

Have your algorithm check in 4 directions instead of 8. (Horizontal, Vertical, and 2 diagonal)

Assuming you first check horizontally and allow matches of 4:

* Look at the block to the left. If it matches increase the # of matched blocks from 1 to 2.
* Keep looking left until you find a block that does not match or the edge of your playing area.
* Then, look to the right and continue adding in the same manner until you find an unmatched block.
* If the number of matched blocks from both directions is greater than 3, then mark the blocks for deletion/exploding.
* Repeat for the other 3 directions.
* Delete all of the blocks marked for deletion.
> 3 votes

---
Tags: pygame, grid, puzzle
---