# Question
Title: Longest path algorithm for roguelike maze generation
I have a simple grid-based map composed of rooms, like this (A=entrance, B=exit):

```
   0 1 2 3
  #########
0 #B# #####
  #########
1 #   ### #
  #########
2 # #     #
  # #     #
3 # #     #
  #########
4 # ###   #
  #########
5 ###A    #
  ###     #
6 ###     #
  #########

```

And I'm stuck trying to make a suitable algorithm to create a path of doors between the rooms, in such a way that the player has to explore most of the map before finding the exit.

In other words, I'm trying to find the **longest possible path from A to B**.

(I'm aware that this problem can be solved for acyclic graphs; however, in this case there can be cycles.)

**EDIT:** Another example where rooms are connected using floodfill, and the exit is chosen as the farthest room from the entrance:

```
   0 1 2 3
  #########
0 #B#     #
  # #-#####
1 # | #   #
  ### #   #
2 ### #   #
  ###-#-###
3 #   | ###
  #-#######
4 #A|     #
  # #     #
5 # #     #
  # #     #
6 # #     #
  #########
```

Note that the path to the exit is not the longest possible path at all.

# Answer
> 6 votes
A possible alternative would be to create a (maximum?) spanning tree using Prim/Kruskal (in order to eliminate cycles) and apply a traditional longest path algorithm on the spanning tree.

However, I'm worried that the spanning tree algorithm will tend to create dead-end branches, forcing the player to backtrack constantly.

**EDIT:** Result of using a Kruskal-based algorithm and placing the exit at the end of the longest branch:

```
   0 1 2 3
  #########
0 #A|     #
  # #####-#
1 # #     #
  ###     #
2 ###     #
  ###     #
3 ###     #
  ###-#####
4 #   |   #
  #-#####-#
5 # ###   #
  #-#######
6 #     #B#
  #     #-#
7 #     | #
  #########
```

# Answer
> 11 votes
I think you're going about this the wrong way. Maximal path in a graph with cycles is technically undefined because it's infinite if the cycle lies between the start and end. There are probably clever ways you can extend/restrict the definition of maximal path, but I don't think that's the best approach here.

You're not trying to model an actual long path (e.g. a robot trying to explore as much area in a map as possible). You're just trying to get the player to explore many rooms.

So, *make the chance the player finds the exit proportional to the percentage of the map explored so far*. Let's say there's X rooms on a level, and the player character has explored Y. Next time the character enters a room, place the exit there with f(Y, X) probability. A trivial example of f might be (Y\*Y)/(X\*X) - e.g. for 10 rooms, there's a 100% chance the exit in the last room, 81% chance it's in the next to last room - and only a 1% chance it's in the first room.

You can tweak the equation however you want to make the game feel right, and maybe even give the player some abilities to make it more likely to generate. The key part is, don't generate the exit until the character actually enters the room. This method is also immune to player knowledge of the dungeon generation algorithm; even if the player has strange movement patterns like the knight's jump in NetHack or teleportation, they're going to have to explore more rooms to find the exit.

If you *must* statically generate the exit, you can use the same idea with a virtual character. Imagine a flood fill starting from the character's position, moving once cell each iteration. The last room to be filled is the room where the exit belongs (in fact, the last cell to be filled is the cell where it's farthest from the player). However, in this case the player has more information about the exit - if they're on the left, it's most likely on the right - and if they can teleport, may actually be able to get there faster than a normal random walk.

Finally, I just finished a roguelike where the exit spawned on the other side of the map from the player character, and then wandered randomly. Some items in the dungeon made it visible on the map, at the expense of getting hungry faster. I didn't do any analysis, but it definitely felt like I had to explore more of the map to find it, and it gave the levels a unique feel.

# Answer
> 2 votes
Here's something to fiddle with:

```
Connect each room with a door to another room.
N = 0.75*TotalNumberOfRooms
Until (pathSize > N) {
  Use A* pathing to get a path from A to B. (G being size of room, or # of monsters)
  if (pathSize < N) remove a connection/door
  if (noPath) choose a different door/connection
  if (room.doors < 1) choose a different door/connection
}

```

I'd remove doors randomly along the path, otherwise you end up with 1 door at the exit, and tons of doors at the start.

I think this is `O(n^2)` so not great for large maps.

# Answer
> 2 votes
2 Stack Overflow posts similar to this one: graph longest path, reference from same post .

# Answer
> 1 votes
I believe you already have great answers, but here is my $0.02 of theoretical solution to the problem.

What you want is NOT the longest path, but longest shortest path. You want the room that is the farthest away, given you are considering the shortest path to the room. This probably sounds confusing, but it is very easy to calculate.

1. Start at your starting room. Mark each of its neighbors 1. They are distance 1 away from the starting room.
2. For each room marked 1, visit each of its UNMARKED neighbors and mark them 2. They are 2 distance away from the start.
3. Continue until you have covered all the rooms. The room with the maximum number is farthest away from the start.

Computing an actual longest path (wont take too long for say 10 rooms) will not work because you cannot make the player take that longest path. So putting the entry and exit in two rooms farthest away from each other is your best bet. To find this, calculate the farthest room from a random room. Then, from that room, find the farthest room. This is called finding the diameter of a Graph, please Google it.

---
Tags: path-finding, roguelikes
---


# Question
Title: I started my journey this way, am I on the right track?
I started my journey to learn games programming from the scratch (I'm a software developer but not in gaming field), I'm targeting iOS games development.

Currently I'm ready "O'reilly iPhone Game Development", then I'm considering reading "Apress Learn iPhone and iPad Cocos2D Game Development".

Am I on the right track? Should I read and learn OpenGL ES? If yes, when to start?

What is the Math type do I need for games development? Algebra and 2D Geometry?

Books like "Challenges for Game Designers" and "Game Design Workshop, 2nd Edition" are on my list also.

I really appreciate if you know a better path to follow.

# Answer
So far you seem to be on the right track. those books can really give you a boost if you are going to develop your games using objective-c. if you have some a good knowledge about obj-c you can easily try changing tech-demo codes, released with the game engine. at least that's the way I usually learn how to work with new tools.

and there are other options for iphone development too. if you feel more comfortable with other languages like c# or c++ or other popular languages, there are engines to based on them.

you may need both OpenGL and mathematics knowledge while developing but just working on the engine helps you learn almost every thing you need to know. and later if you get into any problems, you can easily pinpoint them and directly ask about those specific opengl/math problem you are facing.

As far as I know, there is no game engine using java for iOS, since iOS doesn't support JVM or equivalent softwares. the most related one is JavaScript which is supported by unity. other than that the main programming language you need to use for iOS development is Obj-C, and cocos2d-iphone is one of the most successful gameengines using that language. but you need to learn c++ since there are many libraries written with it. even in cocos2d the main physics engine offered is box2D written in c++.
> 1 votes

# Answer
You might should start learning a little object-C first, but you you do not need to learn OpenGL ES before Cocos2D.
> 0 votes

# Answer
I was in the same situation as you, I'm a developer, but not in the gaming field, and I wanted to target iOS.

The SDK that I found to be productive and fairly easy to get into from a development background was Unity3D. You can code in either their version of Javascript (Unityscript) or in C#. Mind you it is very 3D oriented, but they have sprite engines you can use to create 2D only games.

The other advantage with using Unity is that it doesn't bind you to a specific platform. You can write once and deploy to many platforms (with minor platform specific tweaks perhaps). You can develop on a Mac or a PC which may be more convenient depending on your situation.

Another SDK that I use is GLBasic. It is much simpler and you develop using pure code, and you don't have the fancy interface as Unity (which can be quite confusing for the non-game programmer!). It has all the required 2D gaming commands that you should need, and it also has 3D commands if you wish. It doesn't have built in physics, but you can add the Box2D library which people have done. I love it for its simplicity and how quickly you can get something working.

Both offer a free version to try for as long as you wish, and you can upgrade the licenses if you want to deploy to iOS.

And as far as math is concerned, learning and mastering vectors would go a long way. That and basic algebra, but not much more than in regular development. My biggest learning curve was the graphical side of things, and how to organize a game project. Plus allowing yourself to break traditional programming 'rules' such as globals (etc) to create faster game loops.
> 0 votes

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


# Question
Title: Direct3D and OpenGL Matrix representation
As I read in OpenGL matrices are column major. It means that if I create a 16 element array first four elements are the first column in matrix. Is it the same for Direct3D or any transformation's required.

# Answer
Heishe is right about memory layout and matrices being the same, but his answer is somewhat misleading. Such things as right-handed or left-handed matrices don't exist. Be it a right- or left- handed coordinate system, math and the matrix stays the same, matrix operations give the same result for both of these systems. How we will interpret the data later, thats the difference.

In OpenGL, matrix operations are pre-concatenated, which means concatenated transformations are applied from right to left. Direct3D, however, applies concatenated transformations from left to right.

So what you need to do is to match the order of operation in OpenGL to the order of Direct3D. When writing OpenGL code, you apply the transform that you want to occur first last; when writing DirectX you're doing the opposite. Let's say you just transformed vector `v` in OpenGL by matrices `A` and `B`: `v' = ABv` In Direct3D the same transformation would be `v' = vBA`.
> 7 votes

# Answer
DirectX matrices are right-handed and OpenGL requires left handed matrices, but while OpenGLs matrices are column-major, DirectX's matrices are row-major, so they're layout in memory is the same.
> 0 votes

# Answer
Neither D3D nor OpenGL specify or enforce a matrix handedness. True, the matrix stack functions in OpenGL are RH, but there's absolutely nothing to stop you from writing your own matrix library (or using a 3rd party one) that uses LH coords and loading the result using glLoadMatrixf. Likewise D3D has a full set of both RH and LH matrix functions. This is an old old old misunderstanding and needs to be put to bed.

Regarding row-major vs column major, please see the following: http://www.opengl.org/resources/faq/technical/transformations.htm:

> Column-major versus row-major is purely a notational convention. Note that post-multiplying with column-major matrices produces the same result as pre-multiplying with row-major matrices. The OpenGL Specification and the OpenGL Reference Manual both use column-major notation. You can use any notation, as long as it's clearly stated.
>
> Sadly, the use of column-major format in the spec and blue book has resulted in endless confusion in the OpenGL programming community. Column-major notation suggests that matrices are not laid out in memory as a programmer would expect.
> 0 votes

---
Tags: opengl, directx, matrix
---


# Question
Title: What language or platform is used to develop apps for Google+?
Does anyone know what language or platform is used to develop apps for Google+?

I'm hoping Python, but I know google has a lot of other mediums they could use for this. I'm fine with hearsay as I know the game portion of google+ is pretty new.

# Answer
> 12 votes
App development for Google+ looks to be similar to app development for Facebook. That is to say, you will likely be able to use any language or platform that allows the game to be played in a browser, and you will interface with the API via RESTful style requests (basically making an HTTP call to something like api.plus.google.com)

My guess is that this will mostly translate to a lot of people using Flash, Unity, and HTML5/Javascript.

To add more to this, since I can now check what various games are using: Angry Birds is using HTML5/Javascript (most likely the same one they're using for Google Chrome's app store). City of Wonder is using Flash. Those are the only games I really bothered looking at, but it's enough proof that multiple languages are possible.

# Answer
> 1 votes
Purely speculation here but...

The Google App Engine supports Python, Java and Go for site development. It wouldn't be unreasonable to suggest Google will give all three GAE languages the right hooks for Google+ application development.

My current approach is to use GAE and Users Python API, since to use a Google+ app you will have to authenticate with a Google account.

---
Tags: web, social
---


# Question
Title: Why isn't my player movement code working properly?
I'm making a text-based RPG. One thing I've been trying to implement for a long time now is the ability for the player to move North, South, East, or West. I have my code placed in a MoveBehavior class, which exists in my main Character class.

The problem is that, while my algorithm should work in theory, the locations the player moves to don't change unless the MoveDirection is North/South. East/West, for whatever reason, remains to be the same.

I'll post the class I have (with comments), and then explain in detail further down:

```
public class MoveBehavior
    {
        const int MAX_EAST_WEST_INDEX = 1;
        const int MAX_NORTH_SOUTH_INDEX = 5;
        const int MIN_INDEX = 0;

        //Property Getters...
        public Location CurrentLocation { get { return this.currentLocation; } }
        public int AreaIndex { get { return this.areaIndex; } }
        public int LocationIndex { get { return this.locationIndex; } }
        //Readonly Props
        public readonly Character ClassOwner;
        public readonly int CharacterID; //ID of Character this instance belongs to.
        //Location Handlers
        private Location currentLocation;
        private int areaIndex, locationIndex;

        //Jagged Array of Locations
        private Location[][] locations;

        public MoveBehavior() {} //Default ctor.

        //Constructor takes ID of character, along with a reference to the character object holding it.
        public MoveBehavior (int id, Character character)
        {
            this.CharacterID = id;
            this.ClassOwner = character;

            InitializeIndexes();
            InitializeLocations();
        }

        //Public Methods...

        public void Move(MoveDirection moveDir)
        {
            Location pastLocation = null; //Past location is null to ensure its initialization.

            switch (moveDir)
            {
            case MoveDirection.North:
                this.areaIndex++;
                pastLocation = locations[areaIndex - 1][locationIndex];
                break;
            case MoveDirection.South:
                this.areaIndex--;
                pastLocation = locations[areaIndex + 1][locationIndex];
                break;
            case MoveDirection.East:
                this.locationIndex++;
                pastLocation = locations[areaIndex][locationIndex - 1];
                break;
            case MoveDirection.West:
                this.locationIndex--;
                pastLocation = locations[areaIndex][locationIndex + 1];
                break;
            }

            if (locationIndex > MAX_EAST_WEST_INDEX || locationIndex < MIN_INDEX) //Check to ensure array indexes aren't out of bounds.
            {
                locationIndex = 0;
            }
            if (areaIndex > MAX_NORTH_SOUTH_INDEX || areaIndex < MIN_INDEX)
            {
                areaIndex = 0;
            }

            this.currentLocation = locations[areaIndex][locationIndex]; //Update location

            TravelMessage(pastLocation, this.currentLocation, moveDir); //Output Message

        }

        void TravelMessage(Location pastLocation, Location currentLocation, MoveDirection moveDir)
        {
            int pastNorthSouthIndex;
            switch(moveDir)
            {

            case MoveDirection.North:
                pastNorthSouthIndex = areaIndex - 1;
                break;
            default:
                pastNorthSouthIndex =  areaIndex;
                break;
            }

            Console.WriteLine("{0} has moved {1} from Area {2}, {3} to Area {4}, {5}",
                              this.ClassOwner.Name,
                              moveDir.ToString(),
                              pastNorthSouthIndex,
                              pastLocation.Name,
                              areaIndex,
                              currentLocation.Name);
        }

        void InitializeIndexes()
        {
            this.areaIndex = 0;
            this.locationIndex = 0;
        }

        void InitializeLocations()
        {
            int iterationCount = 0;

            locations = new Location[6][];

            for (int i = 0; i < 6; i++)
            {
                locations[i] = new Location[3];
                for (int j = 0; j < 3; j++)
                {
                    locations[i][j] = new Location("Location: " + iterationCount,
                                                   " ",
                                                   new List<Item>(),
                                                   new List<Npc>()
                                                   );
                    iterationCount++;
                }
            }

        }
    }

```

The idea is to use a jagged array. The first dimension of this array is what dictates where the player is on the North/South coordinate, while the second dimension takes care of the East/West movement.

I use two indexes, an areaIndex(North/South), and a locationIndex(East/West).

If I wish to move North, the areaIndex would increment by one; likewise, to move South, the areaIndex would decrement by one. To move East would require the locationIndex to increment by one; West would decrement the locationIndex by one.

The problem is that, while the code clearly states this in the Move(MoveDirection moveDir) method, nothing happens.

I use the following code:

```
public static class Program
    {
        static void Main(string[] args)
        {

            Character johnDoe = new Npc("ID01");

            johnDoe.MoveCharacter(MoveDirection.North);
            johnDoe.MoveCharacter(MoveDirection.North);
            johnDoe.MoveCharacter(MoveDirection.West);
                    johnDoe.MoveCharacter(MoveDirection.East);
        }
    }

```

To provide this output:

```
John Doe has moved North from Area 0, Location: 0 to Area 1, Location: 3
John Doe has moved North from Area 1, Location: 3 to Area 2, Location: 6
John Doe has moved West from Area 2, Location: 6 to Area 2, Location: 6
John Doe has moved East from Area 2, Location: 6 to Area 2, Location: 7

```

The third line indicates the west movement. To further clarify the issue, John Doe should be moving from Area 2, Location: 6 to Area 2, Location 5. Yet, it doesn't. Thus, my main question is, why isn't this working properly? I have tried a number of different solutions, most of them revolving around using multidimensional and jagged arrays.

# Answer
Because of this:

```
if (locationIndex > MAX_EAST_WEST_INDEX || locationIndex < MIN_INDEX)
{
  locationIndex = 0;
}

```
> 9 votes

# Answer
You are trying to move west from the west-most location, so `locationIndex` becomes -1 and is therefore reset to 0 by the following code:

```
        if (locationIndex > MAX_EAST_WEST_INDEX || locationIndex < MIN_INDEX) //Check to ensure array indexes aren't out of bounds.
        {
            locationIndex = 0;
        }

```

There is few other things in your code which you might want to change:

`MAX_EAST_WEST_INDEX` is set to 1, which makes it impossible to visit some of the areas, I guess it should be set to 2.

The method you use to limit movement to be within bounds is a bit peculiar, as it is now if you go too far east or north you will "roll over" and be at the west-most or south-most location, but trying to go too far in the other directions you will simply be blocked. Unless this is actually the desired behaviour you should make 4 individual statements to handle each of the directions separately.
> 3 votes

---
Tags: c#, algorithm
---


# Question
Title: Why does PIX suggest my frames are rendering out of order?
When my application goes into a fullscreen state my movement is not smooth. It seems like frames are not rendered in the correct order, doing something like: 1, 3, 2, 4, 6, 5, ... making the movement flicker.

For my PIX test, I draw really a low number of primitives (1140 triangle exactly) inside six vertex / index buffers. I clearly see a difference in the GPU frame "ordering" in PIX. Here is the result when in windowed mode:

PIX screenshot1 http://www.s33m3.be/PIX/PIX2.png

You can see that the GPU time needed for the frame is nearly in sync with the CPU time needed to generate it.

But in the fullscreen state here is what I got (same scene, without camera movement):

PIX screenshot2 http://www.s33m3.be/PIX/PIX.png

You can see that each GPU frame processing is split into at least two parts, and the GPU doesn't wait the end of a frame before starting another one.

What could cause this?

# Answer
I swear I added this an answer to this question back closer to when it was originally asked...

Check the "max frames to render ahead" setting in the NVIDIA Control Panel, or whatever the comparable setting in the AMD drivers is if using an AMD card.

I believe it defaults to 3, which would correspond exactly to what PIX is showing you (the GPU is rendering 3 frames ahead of what it's currently displaying).
> 3 votes

---
Tags: directx10, slimdx, pix
---


title: does XNA have 3x3 matrix?

text:
# Question
Title: does XNA have 3x3 matrix?
I've checked intelisence and googled for it but it seems there is no 3x3 matrix in xna. I'm just wondering should I just write a matrix class for xna to work freely with matrix class?

by the way I'm trying to multiply vector3 into 3x3 matrix to have both rotation and translation in one matrix class.

# Answer
> 6 votes
XNA has a 4x4 `Matrix` class (MSDN) which can be used everywhere that you might use a 3x3 matrix - just leave the third or last (depends on your usage) row and column as their identity values. In most cases you should just use that. The only benefit of writing your own 3x3 matrix is if you need the smaller data structure (36 bytes instead of 64).

If you intend to apply *translation* transformations to your 3D vector, then you *need* a 4x4 matrix. The vector implicitly has a fourth element that is equal to 1. Without going through the maths - this allows it to multiply in the translation elements of the matrix. (Details on Wikipedia, see also)

Matrices can be multiplied together to combine multiple transformation operations into a single matrix. For example:

```
Matrix transform = Matrix.CreateScale(2f)
        * Matrix.CreateRotationZ(1f)
        * Matrix.CreateTranslation(10f, 10f, 10f);

```

---
Tags: xna
---


title: Xna Import two files at once

text:
# Question
Title: Xna Import two files at once
i need to import model from two separate files.

I have

* dog.mesh
* pet.material

dog.mesh contains vertices (converted to GeometryContent) and string "pet.material" (reference to .material file)

My MeshImporter that handles .mesh files returns **NodeContent** (one of children should be MaterialEffectContent)

Problem is, that in ContentImporter there is nothing to handle loading of additional assets.

Should pet.material be build by content pipeline in some way? To EffectMaterialContent for example. (Now i build it into MaterialDescription by MaterialImporter - contains string reference to .fx file)

The question is, can you even do things like this in xna? Split something that xna expects to be in one file (MeshContent) into two?

# Answer
There are a few ways to bring in external files. In `ContentImporter.Import` you get a `ContentImporterContext` (MSDN) as a parameter. In `ContentProcessor.Process` you get a `ContentProcessorContext` (MSDN).

Both of these context objects have an **`AddDependency`** method. This signals to the content pipeline that your content importer/processor is bringing in another file. From that point you simply load yout `pet.material` file like you would any file (eg: using `System.IO.File`).

All this does is signal to the content pipeline that another file is being used in the build, and that subsequent changes to that file should (like the main file) cause the content that depend on that file to be rebuilt.

The remaining methods are only available in the content processor:

If `pet.material` is something that the content pipeline knows how to import and process, you can use **`BuildAndLoadAsset`** to load it through the content pipeline. The loaded content can then be embedded in your output content object.

If, however, your `pet.material` might be shared between multiple meshes at runtime, then you might want to use **`BuildAsset`**. The data structures you need to create are somewhat complicated (you need to use `ExternalReference` at build time), but then the pipeline will create a separate output XNB file for `pet.material`, and `ContentManager` will automatically load it for you when required, and share that instance around any meshes that need it.
> 3 votes

---
Tags: xna
---


# Question
Title: How to track position on a map vs position on screen with XNA 4.0?
I'm working on my first XNA 2D game (overhead view), and I'm pondering how to manage the difference in position on screen vs. the position of a sprite on a global map.

The solution I'm currently thinking about is having the map keep track of everything on it, the player, other sprites, etc. The sprites will know where they are on the map, and when `.Draw()` is called on the map it will delegate drawing items to the items themselves, but pass a position to draw on the screen. For instance, something akin to the following:

```
class Map {
    Vector2D ScreenCenter;
    List<DrawableItem> Content;

    void Draw(GameTime gameTime) {
        foreach (var i in Content) {
            i.Draw(spriteBatch, i.Position - ScreenCenter);
        }
    }
}

class DrawableItem {
    Vector2D Position;

    void Draw(SpriteBatch spriteBatch, Vector2D screenPosition) {
        // Draw ourselves at screenPosition
    }
}

```

Is there some better way of doing this? Or am I on the right sort of track here?

# Answer
> 5 votes
I think the best way to do this is to use a `Camera` class which has conversion methods that allow you to convert from "World Coordinates" (which are the pixel/tile coordinates of your map) to "Screen Coordinates" (which are the pixels shown on screen). The `Camera` has a `Location` property (`Vector2`) which is in `World Coordinates` and allows the `Camera` object to figure out what to draw within the `Screen Coordinates`.

This has the added benefit of allowing you to move the `Camera` independently from sprites/characters on the screen.

There's a really good tutorial series on xnaresources.com that goes through designing a tile engine that uses a camera class. I highly recommend it.

I've also gone on with the `Camera` class to make it utilize an interface called `ICameraTarget` (which just defines an `X` and `Y` coordinate for the target, in `World Coordinates`). I implement the interface on my player characters so that it will lock on a player and update itself automatically to their location during the game loop.

*Edit*
To elaborate a bit more: in my game, the map is in tiles, so every player, item, etc has a tile coordinate and an offset (how far off the tile they are in pixels, used for when they are moving across tiles). The `Camera` class has a function that I use in my `.Draw()` that is called `WorldTileToScreen(int tileX, int tileY)`. This returns a `Point()` or `Vector2()` (I use point, but it's up to you). This takes the player's (/item's/etc.) X/Y values (in tiles) and multiplies them by the width and height of the map's tiles in pixels (respectively). It then subtracts the `Camera`'s `Location` property (which is an X/Y value) from that to find the object's `Screen Coordinates`. Then, I add the object's offset to those values to that to get the position to draw the object on screen.

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


title: XNA Tile from Screen Location

text:
# Question
Title: XNA Tile from Screen Location
I have a tile based game that is in a semi-isometric view created by a transformation. The tiles are created by a Texture2d rendered on a 3d surface.

I am using the following code for transformation:

```
View = Matrix.CreateLookAt(new Vector3(0, -1.1f, 1.6f), new Vector3(0, 0, 0), new Vector3(0, 53, 0));
Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi - 2.4f, 4.0f / 3.0f, 1, 500);

quadEffect = new BasicEffect(device);

quadEffect.World = Matrix.Identity;
quadEffect.View = View;
quadEffect.Projection = Projection;
quadEffect.TextureEnabled = true;

quad = new Quad(new Vector3(0, 0, 0), Vector3.Backward, Vector3.Up, 3, 3);

```

My problem comes along when I attempt to get the current tile that I am hovering the mouse over. I have a mouse X and Y however I can't seem to figure out how to transform these screen coordinates into a tile X and Y. The tiles are 128px by 128px; however, after the camera transformation they are smaller on the top and larger on the bottom(to create the isometric view)

I've tried transforming the mouse X and Y with the same projection matrix. However, this didn't work. I think it is due to the view matrix not being taken into account... sample below:

Vector3.Transform(new Vector3(Mouse.GetState().X, Mouse.GetState().Y, 0), Projection);

This image may provide more information... is also shows the hours I've put into figuring this out:

# Answer
You can use Viewport.UnProject with two source values:

A(MouseX, MouseY, 0) B(MouseX, MouseY, 1)

You will get the two unprojects points that can be used to get a ray, then you have to get the ray intersection with the plane where are the tiles.

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.viewport.unproject.aspx
> 3 votes

---
Tags: xna
---


# Question
Title: Why can't I add a float4 read from a Texture2D.Sample in the Vertex Shader?
These lines work (compile fine):

```
float4 offset = HeightMap.Sample(HeightSampler, input.Texcoord);
input.Position.xyzw += float4(0, 1, 0, 0);

```

These do not (any use of offset together with input/output Position causes the error):

```
float4 offset = HeightMap.Sample(HeightSampler, input.Texcoord);
input.Position.xyzw += offset;

```

No matter what I try to do to use the offset values to change the positions it breaks:

```
float4 offset = HeightMap.Sample(HeightSampler, input.Texcoord);
matrix<float, 4, 4> offs = {
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    offset.x, offset.y, offset.z, 1
};

output.Position = input.Position;
output.Position = mul(output.Position, offs);

```

Debug output:

```
(32,9): error X4532: cannot map expression to vs_5_0 instruction set
(62,19): There was an error compiling expression
(49): Error compiling effect hr=S_OK (0x00000000)

```

Anyone have an idea why?

# Answer
The problem is that you can't use a simple Sample() call in the vertex shader as it doesn't know what mipmap level to sample from, so the data coming back can't really be a float 4 and the call just doesn't really make sense. In the pixel shader, you need to use:

```
float4 offset = HeightMap.SampleLevel(HeightSampler, input.Texcoord, 0);

```

Changing to that worked perfectly.

http://www.gamedev.net/topic/604632-texture2d-sample-in-hlsl/
> 11 votes

---
Tags: textures, hlsl, heightmap
---


title: How do I enable higher FPS in XNA 4.0?

text:
# Question
Title: How do I enable higher FPS in XNA 4.0?
I created a `FpsCounter` `DrawableGameComponent` (linked to code, it's longish). It works great: It displays 60.0 fps normally. If I artificially slow down the game loop, it drops.

My 'game' at the moment is a single keyboard-controlled sprite, so it should be possible to render more frequently than 60 frames a second.

I figured turning off vertical synchronization would increase the FPS cap:

```
public Game1()
{
    _graphics = new GraphicsDeviceManager(this)
                    {
                        PreferredBackBufferWidth = WindowWidth,
                        PreferredBackBufferHeight = WindowHeight,
                        SynchronizeWithVerticalRetrace = false,
                    };
    _graphics.ApplyChanges();
    Content.RootDirectory = "Content";
}

```

However, even though the above code seems like it should turn off vsync, it doesn't seem to be. Is there something wrong with my constructor, or perhaps my FPS calculations? Or is there something else that may be limiting the frame count?

# Answer
if Game.IsFixedTimeStep is true the update method will be called every 1/60 seconds

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.isfixedtimestep.aspx

"The default value for IsFixedTimeStep is true."
> 11 votes

# Answer
It depends on your video card settings (in Windows). I had the same issue and than I found that my nVidia card has its own vsync settings in control panel where vsync can be set to forced-on mode (application settings will be ignored in this case).
> 3 votes

---
Tags: xna, xna-4.0, optimization, frame-rate, vsync
---


# Question
Title: Examples of wall avoidance algorithm dealing with rectangles instead of lines?
I have a tile based engine and in the middle of translating out the example wall avoidance alogrithm in the book AI programming by example. I was wondering if the method below can be modified so that it takes a rectangle instead of vector C and D and still produce the same output ?

```
/-------------------- LineIntersection2D-------------------------
//
//  Given 2 lines in 2D space AB, CD this returns true if an
//  intersection occurs and sets dist to the distance the intersection
//  occurs along AB. Also sets the 2d vector point to the point of
//  intersection
//-----------------------------------------------------------------
inline bool LineIntersection2D(Vector2D   A,
                               Vector2D   B,
                               Vector2D   C,
                               Vector2D   D,
                               double&     dist,
                               Vector2D&  point)
{

  double rTop = (A.y-C.y)*(D.x-C.x)-(A.x-C.x)*(D.y-C.y);
    double rBot = (B.x-A.x)*(D.y-C.y)-(B.y-A.y)*(D.x-C.x);

    double sTop = (A.y-C.y)*(B.x-A.x)-(A.x-C.x)*(B.y-A.y);
    double sBot = (B.x-A.x)*(D.y-C.y)-(B.y-A.y)*(D.x-C.x);

    if ( (rBot == 0) || (sBot == 0))
    {
        //lines are parallel
        return false;
    }

    double r = rTop/rBot;
    double s = sTop/sBot;

    if( (r > 0) && (r < 1) && (s > 0) && (s < 1) )
  {
    dist = Vec2DDistance(A,B) * r;

    point = A + r * (B - A);

    return true;
  }

    else
  {
        dist = 0;

    return false;
  }
}

```

# Answer
> 4 votes
Sorry to state the obvious, but rectangles are essentially 4 lines.

Why not just reuse the code and have something like:

```
RectangleIntersectionWithLine( Vector2D a, Vector2D b, BoundingBox box )
{
    LineIntersection2D( a, b, box.Min, Vector2D( box.Min.x, box.Max.y ) );
    LineIntersection2D( a, b, box.Min, Vector2D( box.Max.x, box.Min.y ) );
    LineIntersection2D( a, b, box.Max, Vector2D( box.Min.x, box.Max.y ) );
    LineIntersection2D( a, b, box.Max, Vector2D( box.Max.x, box.Min.y ) );
}

```

I leave the return values, etc up to you.

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


# Question
Title: Generating island terrains with Simplex Noise (C#/XNA)
I've got one little question: Is there any code or sample which shows how the simplex noise works? I cannot find anything about it... How should I implement it, without the knowledge how the algorithm works?...

The other question is: Is the simplex noise a good algorithm for island generation? I need huge islands (really huge), with different layers (sand, gras, stone) and clearly visible height-differences, which have soft-edges, so you can go out/into water without jumping over uneven surfaces.

# Answer
Ok thanks to all for the help :)

2 days ago i found "Libnoise" and a good C# port. I will take this one, because there´s a renderer which renders smoother heightmaps :)
> 1 votes

# Answer
My noise generator in C#, based off this:

```
static class NoiseGenerator
{
    public static int Seed { get; private set; }

    public static int Octaves { get; set; }

    public static double Amplitude { get; set; }

    public static double Persistence { get; set; }

    public static double Frequency { get; set; }

    static NoiseGenerator()
    {
        Random r = new Random();
        //LOOOL
        NoiseGenerator.Seed = r.Next(Int32.MaxValue);
        NoiseGenerator.Octaves = 8;
        NoiseGenerator.Amplitude = 1;
        NoiseGenerator.Frequency = 0.015;
        NoiseGenerator.Persistence = 0.65;
    }

    public static double Noise(int x, int y)
    {
        //returns -1 to 1
        double total = 0.0;
        double freq = NoiseGenerator.Frequency, amp = NoiseGenerator.Amplitude;
        for (int i = 0; i < NoiseGenerator.Octaves; ++i)
        {
            total = total + NoiseGenerator.Smooth(x * freq, y * freq) * amp;
            freq *= 2;
            amp *= NoiseGenerator.Persistence;
        }
        if (total < -2.4) total = -2.4;
        else if (total > 2.4) total = 2.4;

        return (total/ 2.4);
    }

    public static double NoiseGeneration(int x, int y)
    {
        int n = x + y * 57;
        n = (n << 13) ^ n;

        return (1.0 - ((n * (n * n * 15731 + 789221) + NoiseGenerator.Seed) & 0x7fffffff) / 1073741824.0);
    }

    private static double Interpolate(double x, double y, double a)
    {
        double value = (1 - Math.Cos(a * Math.PI)) * 0.5;
        return x * (1 - value) + y * value;
    }

    private static double Smooth(double x, double y)
    {
        double n1 = NoiseGeneration((int)x, (int)y);
        double n2 = NoiseGeneration((int)x + 1, (int)y);
        double n3 = NoiseGeneration((int)x, (int)y + 1);
        double n4 = NoiseGeneration((int)x + 1, (int)y + 1);

        double i1 = Interpolate(n1, n2, x - (int)x);
        double i2 = Interpolate(n3, n4, x - (int)x);

        return Interpolate(i1, i2, y - (int)y);
    }
}

```

It isn't commented, but the main parts:

Seed is a value used to make it random - so you don't generate the same thing each time. Here I have put it in the NoiseGenerator.

Amplitude, Frequency, Persistence, and Octaves are explained in the article - they basically affect what the resulting noise looks like.

`NoiseGenerator` function is literally a PRNG - give it an input, and it generates a random number with that as a seed.

`Noise` is what you call to get a noise value. I found the values were around -2.4 to 2.4 (actually about 2.40032483 or something so they are clamped) and I fixed them to doubles between `-1 and 1`.

I have not had any speed problems with this. I was rendering a 400x400 grid of 1x1 sprites with values set by this and was getting only minor lag (and that was recalculating noise each frame).

For the island generation, check out this question \- in particular, this link is almost exactly what you want, albeit in AS3.
> 1 votes

# Answer
If you haven't come across it already, Stefan Gustavson's Simplex Noise Demystified is a good explanation of how the algorithm works.
> 0 votes

---
Tags: xna, 3d, procedural-generation, terrain
---


# Question
Title: What is the best engine for my first serious 2d game?
What game engine/graphics engine should I use for my first indie game? I'd like to add that this is not my first game, I've previously used Allegro for 2d development (pong, chess and stuff).

I am open to suggestions for other engines.

I was thinking about a game like "The legend of Zelda" for the NES (just to give you an idea what I was planning).

I've heard of SDL, I've used Allegro, my friends use OpenGL, what is the best for starting? (SDL seemed a bit hard, judging from their Wiki, a lot of stuff I haven't used before).

BTW, the language is C++.

# Answer
> 6 votes
First of all, what you're looking for isn't really an engine. You're looking for a graphics API or a graphics API Wrapper to do your drawing.

I can recommend SFML. It's a C++ library that manages most of the basic things that everyone needs for you.

It features a relatively powerful graphics part which wraps around OpenGL, but also includes basic support for window-management, input (keyboard, mouse, joystick/gamepad), audio (playing sounds and music) and networking.

Since it's C++ and entirely object-oriented, it will be very simple to understand. For example, loading an image and displaying it more or less looks as simple as this (in SFML2.0):

```
sf::Texture texture.
texture.LoadFromFile("blabla/test/supermario.png");

sf::Sprite sprite;
sprite.SetTexture(texture);

//somewhere else
window.Draw(sprite /*, myAwesomeShader Optional shader argument */);

```

Apart from the superior code-design, it's also a lot faster than the current version of SDL and has more features (if you use the basic SDL libs).

I can really recommend it if you're using C++.

Also, if you're going to pick SFML, start with SFML2 instead of 1.6. It isn't officially released yet, but it is going to be very soon and not a lot will change in the API until then. The latest SVN snapshots of SFML are always available on the download page.

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


# Question
Title: What are some techniques for designing fun, challenging Mario-style platformer levels?
I have everything I need to make a Mario type game. I just have no idea how to design the levels to make it challenging or fun. Any tips?

The only way to kill enemies is by jumping on them, so I thought it would be too hard to make a boss. I was just going to make the last level long. Is this a bad idea?

# Answer
> 13 votes
Just a short list of things I could come up with.

If jumping on enemies and jumping in general are your only two gameplay mechanics:

* Gradually introduce new enemies with new movement patterns.
* Gradually introduce new obstacles.
* Gradually increase jump precision / speed / timing requirements
* Consider making the game harder by having your character move faster or with less precision. Or make character movement super-tight and the levels super difficult (Super Meat Boy).
* Instead of bosses you could have hard jump sequences. Just remember not to frustrate the player too much.
* Introduce things as walljump or gravity manipulation to spruce things up?
* Make sure that the player dies because he's bad not because you trick him. (eg. one hit kill spikes that teleport out of nowhere(I Want To Be The Guy))

# Answer
> 9 votes
Here's another article about Mario-style level design.

And here's an article I came across some time ago while researching procedural level design for platform games. It discusses difficulty and design patterns.

Try to strike a balance between tricky platforming sections and places to "rest." Note that very few platform games are constantly challenging but, instead, provide places to pause and revel in the completion of a difficult section or psych themselves up for the next block. Often, this is done through obvious checkpoints but it doesn't always have to be this discrete.

Remember that in Super Mario Bros, there *are* bosses even though your primary attack is jumping (fireballs notwithstanding). Bowser can't be defeated by jumping on him but getting past him is a challenge that breaks from the jump-on-everything's-head mold that many simple platformers exhibit. Additionally, Super Meat Boy features several different types of bosses, many with a unique gimmick. But you don't actually attack any of them directly since you can only jump. Not being able to attack doesn't make bosses out of the question; it can actually make them better.

# Answer
> 3 votes
One thing that has always stuck out to me about the NES/SNES Mario games is that they give the player the opportunity to show off.

This can be done by making some of the trickier sections optional. So the player *could* choose to wait for a moving platform to cross the gap, but it's more fun to nail a jump off three flying enemies and score some extra coins in the process. Or the player *could* wait for the piranha plant to retreat back into its pipe, but it's more fun to make the narrow leap over its head. Reward the players when they complete a tough section, but you don't have to penalize the ones who decide to take the easy route (unless you're going for the super hard twitch platformer style). Give players the chance to identify bonus areas, so they can tackle them later when they have more confidence in their skills.

As for bosses, a lot of the bosses in "simple" platformer-style games are based around simply surviving their patterns until they reveal an opportunity to attack. Though there's nothing wrong with having the final challenge be jumping challenges rather than a boss enemy. If you decide to do that, I would suggest throwing in some kind of new mechanic to pressure the player, rather than just having a longer level.

# Answer
> 3 votes
From The Big List of Game Design, here are several articles that discuss Mario level design in particular. There's a wealth of information in them, as well as in the original article that lists them.

Super Mario Bros. 101

Super Mario Bros 3 Level Design Lessons, Part 1

Super Mario Bros 3 Level Design Lesson, Part 2

level design lesson: to the right, hold on tight

A really important takeaway in several of these articles is how the level design teaches the player *how* to play the game. You need to create a situation where they can first learn that they can jump, then learn that jumping on something can have an effect on it before you toss them into a level with monsters that can be jumped on.

# Answer
> 1 votes
If your game is a commercial project, or you plan on going the commercial route in the future, one test tool you might want to research is heat mapping. The following link talks about it, and www.gdmag.com had an article on it in their Sept 2010 issue (with a download of python code). The article was by Chris Pruett, entitled "Hot Failure". His resources were Goerg Zoeller's BioWare telemetry talk (http://gdc.gulbsoft.org/talk) , Replica Island player metric snapshot (http://replicaisland.net/index.php?view=en/player\_metrics.php) and the use of ImageMagick (www.imagemagick.org).

http://lucasartsworkshop.wordpress.com/2009/10/09/telemetry-data-heat-maps-and-unlearning-what-you-have-learned/

You basically run your game with the heat map system collecting data and prioritizing by color. One test would be player lives lost, the map would show literally, problematic "hot spots" where an enemy battle was more difficult that others, or where you require a difficult move or jump to move further through the level. If your game is for personal or non-commercial use, heat-mapping would be considered over-kill.

# Answer
> 1 votes
found this the other day. auto generates the levels based on the players skills :) is a lot of fun to play and learned a lot from it.

http://eis-blog.ucsc.edu/2010/09/a-probabilistic-multi-pass-level-generator/

---
Tags: 2d, platformer, level-design
---


# Question
Title: Is there a simple 2D Android barebones starter project?
I'm looking at creating a tower-defence-style game on Android, developed in Java. I'm spending a lot of time trying to just get a background image (drawn onto a canvas) that pans/zooms within the bounds of the screen etc. that I will eventually draw my game onto.

It seems to be a lot of work just to get theses basics working correctly. Is there a simple barebones project that has this stuff taken care of that I can build my game on top of?

# Answer
> 1 votes
What you may be looking for is an engine. In that case, refer to this question: https://stackoverflow.com/questions/5206089/game-engine-for-android. I would recommend AndEngine or LibGDX. However, the best way to learn, in my opinion, is to power through the beginning things, learning along the way. Ask questions here and on StackOverflow and you'll be able to make your own "barebones" project in no time!

---
Tags: 2d, android
---


# Question
Title: Need help making a semi-simple javascript game
I'm currently trying to make a fairly simple game in JavaScript and it isn't going too well.

Before I started, I thought I'd only need to know three things (on top of what I already know) which were:

1. How to 'spawn' an object (i.e. a bullet) by pressing an on-screen button.
2. How to make that bullet move across the screen.
3. How to make that bullet collide with something.

I thought the first two would be pretty simple, but I cannot find anything online to help me with them. Source code and tutorials appear to be either too simple or too complicated, and I'm starting to worry this project will be a lot more complicated than I thought.

So, can anyone help me do any of the listed things? If so it'd be much appreciated!

# Answer
Though the game idea you're talking about is pretty simple, there's a fair bit of work that has to go into coding such a game in JavaScript, or any other language for that matter.

Fortunately though, there are lots of libraries available that can help you out with a lot of the details, like spawning a bullet, moving it, and detecting when it hits something.

My advice would be to go check out a JavaScript game library such as gameQuery. gameQuery is one of many game libraries available, and it has a good introductory tutorial that you might find useful.

So if you want to get started with a basic game, head over to http://gamequery.onaluf.org/tutorials/1/ and read the tutorial on creating a basic game with gameQuery and JavaScript. Do the tutorial first as is, and then later modify it to change how the game looks or behaves if you'd like something different. Working from an existing game (modding as it's called sometimes) is a great way to get started -- a lot better than starting from scratch.
> 3 votes

---
Tags: javascript
---


# Question
Title: Where to start with hardware-specific low-level programming?
Seeing as today's machines have insane computing power and near endless memory, it's tough for a hobbyist programmer to actually hit the limits of his machine without doing something totally boneheaded. This raises a question: Is there a machine (be it a computer or a console) from the past that would be a good learning platform for someone that has never touched low-level code? I'm very much looking at this from the perspective of someone that wants to understand exactly how to get the best out of the specific set of hardware a machine has.

I'd imagine that the internet probably has manuals for most well known older machines, and it shouldn't be too hard to find an emulator of some sort either. I'm just at a little bit of a loss when it comes to actually choosing a good platform to go for. Any ideas?

Obviously if someone has ideas that don't fit the exact parameters of the question, I'm open for that as well.

# Answer
> 5 votes
You don't really need to go back that far to find limited devices. As we are on gamedev here, I'd suggest looking at the Nintendo DS with its 67 MHz processor and 4 MB RAM (see here for some specs).

While development for the DS is limited to licensed developers, there is a pretty active homebrew scene and there are several emulators. You can also run your programs on the actual device using special gamecards. A really detailed reference can be found here. The software you need for development is known as devkitARM and can be found here. There is lots of good information on DS development around the internet.

However, I can't say anything about the legality of homebrew DS development.

# Answer
> 3 votes
Returning to a legacy machine which you have no emotional tie to seems pretty masochistic. If I were doing it I would choose the first computer I had, Apple \]\[c...

J2ME Java for mobile phones might be another suitable choice : Eclipse is free and test devices (for example S40, S60 Symbian phones ) easily available for cheap. Even modern smartphones are very limited, though they are reaching something in the direction of PlayStation 1 or better as we speak. An example 256 Mb RAM can be tanked fairly quickly if you load up everything in a medium-sized game.

# Answer
> 3 votes
I say go for modern X86, just because the processor is fast doesn't mean you can't benchmark and optimize. And really, it is not just more useful to know a modern architecture, the new processors also have a quite different performance profile.

In the old days a processor would primarily be limited by it's ability to perform calculations, today it is much more important how fast it can access data and resolve branch instructions, because getting plenty high performance in raw calculations is no feat.

At best learning an old architecture would be a waste of time, at worst you teach yourself the wrong stuff and end up writing slower code for modern computers.

---
Tags: performance, hardware
---


# Question
Title: Should I learn 2d game development before 3d?
I'm an iPhone app developer. I want to get into iOS gaming. The question is-should I start with learning 2D like Cocos 2D or Corona SDK before learning 3D gaming like Unity? I'm more interested in 3D gaming, but do you think that knowing 2D gaming is a prerequisite to learning 3D development?

# Answer
> 11 votes
**It depends on how strong you are with mathematics,** *and* **3D game programming concepts**.

2D you can get by using only concepts of x,y positions and velocities (and adding and subtracting them - basically vectors) and 2D box collision.

In 3D, you have to worry about a lot more math: projection matrices, viewing matrices, frusta..

In addition, you have to interact with a ***much richer set of functions*** from the drawing API you're using, (just by virtue of the fact that you're doing 3D, so you have to learn a lot more functions that deal with 3D).

Microsoft XNA has **excellent** support for starting out in 2D, and makes rendering easy using SpriteBatch. As soon as you venture into 3D, you automatically have to learn VertexBuffer, or Model, and then comes ModelBones and everything else that goes with it.

You're best off starting 2D just because the concepts you need to grasp is less (2D sprites? A cakewalk!). After you have some experience under your belt, then you should be fine doing 3D.

# Answer
> 9 votes
The only fundamental difference between 2D and 3D game development is whether or not you use the 3rd axis. If you're using an engine like Unity you can just as easily make 2D games as 3D games by simply using an orthographic camera projection and sprites instead of models.

That being said, if you're not using an engine that does a lot of the 3D heavy lifting for you, it is a lot harder. See the answer to this question: What to consider when deciding on 2D vs 3D for a game?

What you should do is decide what game you want to make and the art and design will tell you if it needs to be 2D or 3D.

# Answer
> 5 votes
I agree with Tetrad that you should think about the art and design and that will lead you if it needs to be 2D or 3D. I also will say that it may be a good idea to create a 2D game first so that you won't have to think about the harder things that come along with 3D games. Also, one thing to realize is that the brain will process less information with 2D games which is what you want for a more casual experience.

If you look at most of the successful indie games over the passed 3 years, many of them were 2D.

http://www.braid-game.com/
http://limbogame.org/
http://supermeatboy.com/
http://www.andyetitmoves.net/

So a company can be successful making just 2D games. The success of games comes from game mechanics, story, aesthetics, and technology. Otherwise known as the tetrad. I'm getting off topic so I digress.

# Answer
> 3 votes
Keep in mind, it will be simpler for you to get 2D art assets to practice with. So while I don't think learning 2D game development is a prerequisite to learning 3D game development (either way the game code on top of the graphics code is pretty much the same) I would still recommend most beginners start with 2D games unless you already have a solid resource for 3D graphics (eg. you'll be learning alongside a buddy who is a 3D artist).

Code-wise, the difficulty depends on what you are trying to learn and what engine you will be using (and in particular if you will be writing your own engine). Low-level 3D graphics code is much more complicated than low-level 2D graphics code, but if you will be using an engine like Unity then you won't be writing low-level graphics code. The code for a 3D game built in that engine is no more complicated than the code for a 2D game. Indeed, it may be considerably less complicated, depending again on the specific engine you are talking about.

---
Tags: 2d, 3d, ios
---


# Question
Title: Design pattern on class level, how to do separation of concerns through mvc or alike?
Say i had a Monster class

```
public class Monster {

}

```

Now this class has a set of properties like

```
int health
int speed
int weaponDamage

```

which details the core information about the monster.

in addition it also needs gui information stored in the model. probably something like this:

```
int positionX;
int positionY;
int positionZ;
int rotation;

```

So let's say those are the main properties in our Monster definition. Now we have a couple of methods that do things (besides data getters and setters).

For example:

```
public void move(){
  //do changes to position.. and rotation variables
}

public void eventIncomingDamage(Projectile p){
  //Incoming projectile did damage to monster
}

public void doDamage(Target aTarget){
  //fire off an damage event on target.
}

```

So, my question is, how should one go about separating the different data types and methods in such a way it conforms to separation of concerns? Should i have one MonsterController which has the `move,eventIncomingDamage and doDamage` methods, a Monster class which only has the core information (`health,speed,weaponDamage`) and what about a MonsterRenderer class (view), how should it fit into all this?

In my example "solution" im thinking along the lines of the MVC pattern. But are there other patterns that should be used in combination or instead?

How would you go about organizing this code into managable and separated blocks?

I hope this can start a good discussion around structuring data, actions and events.

# Answer
> 5 votes
Let's stir up the discussion with a somewhat provocative point of view. It's possible for a mind to create abstractions as beautiful as a crystal castle in the sky, and in many games it would be just as useful.

Personally, I found it quite beneficial for game architectures to "flow from below": first think about data, then about feasible limitations of various kinds, and only after that think about ways of manipulating said data, instead of conjuring up some architecture based on a currently opened page of a book about patterns. That way your code will be structured and effective in a way most optimal for your game and your task. Otherwise it is a potential end in a Procrustean bed of patterns and imaginary data. It's not that bad, especially for an enterprise application with a team of fellow developers on an outsorce basis, maybe even for beginner game developer, but we can do better. For an example on a code organization of a very complex game I would recommend looking at "Jagged Alliance 2" sources. It's definitely not the most beautiful thing in the world, but since it's basically naked functions operating on data, it shows a way of game development from times when patterned thought process wasn't a devotion.

Let's say we're developing a pathfinding for a turn-based strategy. In theory it's possible to make the pathfinding architecture ideal and abstract to the point where we can make a RTS instead of a TBS using the same architecture with ease. Do we need to do that? Pathfinding for a single unit of fixed size in a turn-based tactical game with small fixed map has substantially different data from a pathfinding for a lot of units with different sizes and traversal capabilities in real time strategy with dynamic map of large size. So in reality such approach will yield us a slower pathfinding, which will frustrate gamers, with more entities than needed for an actual task, which will frustrate developers, and only a limited ability to be more agile before it would be needed to rewrite a pathfinding engine. So nope, we don't need to design overly complex interactions to support something illusional unless developing a generic game engine or construction set.

Back to the original monster case. The most obvious, clear and blatantly generic way to express intent of moving a monster would be:

```
 monster.Move(position);
 // or oif there is a reason for logic extraction,
 MoveEngine.Move(monster, position).

```

It's good for a game where you often move single monsters around by hand, i gueess.

But what if our game is about wasps, and they come in numbers, and if even a single wasp comes somewhere, other needs to be notified to come after him soon? And wasps are actually controlled by evil wasp hiveminds competing for power? Moving a single monster would become like a 1% of all move cases; it's counter-productive to guide every wasp manually, and now moving intent expressed like this:

```
enemyHivemind.CurrentAI.AddNewTask(new ScoutTask(position));

```

Then AI engine will check that swarm can move, has scouts, can find path to the position, and create appropriate move behaviour it the to-do list with the highest priority, which will be executed the nearest update, where it fill finally move that single scout one way or the other, it doesn't matter to us much. Needless to say, all movement routines and pathfinding would be optimized for a swarm movement, not for a single unit.

You see in our mind we started with a generic single monster as a main entity, but with the actual game in mind it quickly can become just a small and insignificant part of something greater, basically a set of data for others to operate on.

**So the main point is, think about your data, write a design document first, choose your architecture later**, and it will be a good choice whether you decide to use naked objects, MVC, PAC, MVP, SOA, event-driven entity systems or not — in your mind you've already won.

# Answer
> 4 votes
There is a conceptual misunderstanding in your question. positionX is to the same degree a "core" property as health or speed is. In fact, speed is nothing else than the length of the rate-of-change-vector of the position.

This conceptual wrong distinction leads to a bad design. The update- and the render-logic use the same properties, i.e. position, rotation and even health. health can be rendered as a number above the monster for instance, there is no fundamental difference between those properties.

The entire question is trying to force a design pattern into data rather than the other way around, drawing a line where no such line exists.

```
How would you go about organizing this code into managable and separated blocks?

```

This data from your question:

```
int health
int speed
int weaponDamage
int positionX;
int positionY;
int positionZ;
int rotation;

```

simply belongs into 1 class. Don't over engineer, don't put unnecessary layers of complexity.

# Answer
> 1 votes
One way of doing it:

Each entity consists (as you said) of

1. EntityModel
2. EntityRenderData
3. EntityController

To process these:

1. Have a GameController class which runs all core logic by running through every EntityController on each update.
2. Have a GameView class which extracts necessary rendering information from each EntityRenderData

(For both of the above, you can add custom logic that runs aside from entity processing.)

You can also have a GameModel which holds your "current" entity list, your "just added" entity list and your "to remove" entity list. You update your "current" list at the end of each Controller update by removing those "to remove" and adding those "to add". It can further add more general world data that doesn't specifically apply to entities, if necessary.

As an aside, you can have your GameController and your GameView on the same or separate timers in order to update. Separate is good if you want to decouple view updates from logical updates as suggested by Gaffer.

You'll obviously need to use dependency injection at the appropriate times to ensure everything has a reference to everything else (V-\>M, C-\>M, C-\>V) at both the Game and Entity levels.

---
Tags: architecture, java, design-patterns, mvc
---


title: Who does the AI calculations in an MMO?

text:
# Question
Title: Who does the AI calculations in an MMO?
I am building an MMO and want to add NPCs. The thing is I don't know the basic design. What does the calculations, the clients or the server? I would understand the server calculating events and reactions, but when it comes down to pathfinding and position and movement of player, who calculates that?

Who calculates the AI the server or client? I couldn't imagine the server calculating the pathfinding, position, movement and so on. Please I need help understanding this, thanks, anything will help.

# Answer
Most MMOs these days have anything important done server-side, for safety reasons. You can't off-load much to the client, which is why one of the first things axed are AI routines. I think most developers consider client-side to be hackable as a rule, not an exception.

Scalify's Badumna ( http://www.scalify.com/badumna.php ) tries to off-load part of it on the clients in that they'll have calculations done client-side and sent to each other; some data is also sent to an authorative peer to be validated before it's passed on to clients, just like a dedicated server. The issue is that ALL data in a multiplayer game MUST be sent through an authoritative peer if you want to prevent cheating. I brought up Badumna as it seemed the closest to what you might want, but even that won't be able to catch cheaters -- it might catch some, but anything critical (ie. everything, pretty much) has to be done server-side.

I might expand some on Badumna, because it could still be something you'll find useful (but I urge you to reconsider off-loading anything important on the clients, because the clients WILL cheat).

Badumna offers a hybrid architecture for data operations. It provides complete control to the developer in deciding what is critical (and must be verified) and what isn't (and so can be sent by the decentralized network).

If an MMO requires that every single bit of information has to be verified then Badumna will function as a client-server solution. However, I believe that there are different categories of MMO applications with varying requirements. For example, quite often an MMO will have combat zones where players are likely to cheat and hence every bit of information has to be verified. However, there are also zones where players can only walk/run/dance/chat. Such zones do not require complete verification and can utilize Badumna's decentralized network and benefit from the scalability that it can offer.

Secondly, Badumna provides additional security features that developers can access such as identity protection (so that users cannot pretend to be someone else), complaint proxy (allowing clients to be configured to report malicious/cheating players to a trusted source), and black listing (banning malicious players from the games).

I've not really explored Badumna that much, so there migh be issues and features I'm unaware of, but at least I've given a cursory glance on it.

tl;dr: the client should really just be a keyboard and mouse hooked up to the internet.
> 26 votes

# Answer
The short answer is that for a standard MMO, the AI calculations are always performed by the server.

Some games will have the client try to predict the AI, so that NPCs will appear to react more quickly, but that's just an illusion; the real NPC is always controlled by the server.
> 9 votes

# Answer
An MMO is a public- (Internet-) facing server. Anything that you want to be able to control completely should not be accessible to the public, otherwise you risk allowing an attacker to control NPCs. Unless you're doing some sort of encryption on your commands (which will impact performance), you can't trust the client to be running only your own code.

Predicting NPC movements on the client to compensate for lag is a great idea; you could theoretically include as much of the AI behaviour as you wanted in the client program and have them sync up periodically - but allowing the client to dictate the behaviour of an NPC would grant the client the potential to mess with the game world. If the client descynchronises from the game world on the server then you'll end up with uncontrollable rogue NPCs.

Which is a shame, really, because distributing AI over clients could impact scalability.
> 5 votes

# Answer
Usually the server should calculate or validate every data passed to or received from the client. But It depends on how much you can trust the client and how important that calculation is. Sometimes the main calculation could be done on the client and the server might be able to use a simple method to validate the resulting data.
> 2 votes

# Answer
To build on the other answers, the "offload and verify" strategy could indeed be useful, in situations where the verification is easier than the original calculation (or where only occasional spot checks would be enough to catch cheaters).

For example, if you had the client do A\* pathfinding and send the results to the server, all the server would have to do is check that a) the path is valid, and b) there is no shorter path. Checking path validity should be easy, and checking optimality *could* be easier than finding the optimal path to begin with, since you now have an upper bound on the length of the paths you need to check. (In particular, if the client returns a straight-line path, it is obviously optimal as long as it is valid.) To be honest, I have no idea whether this particular trick would be useful in practice, but I see no fundamental obstacle to it.

Do note, however, that if you offload NPC AI to the clients, then a hacked client could potentially use it to predict NPC behavior in advance. For some types of games or situations this could be a serious issue.
> 1 votes

# Answer
It's probably best to have some simple AI routines and game-critical calculations on the server side, while handling the complex non-game-critical operations on the client side.

For example, the server knows where a hostile NPC is and where the player characters are. When the player character gets within range of the NPC a server-side calculation can be done to see if the NPC should attack the player, and a simple pathfinding routing can be done to determine how long it will take the NPC to reach the player.

Once the NPC has been transitioned to the attack state the client can deal with animation and fine-grained path finding. When the NPC is close enough to the client to attack the server can perform calculations to see if the attack hit, what the damage was, etc...

You'll want to make sure that any calculations that truly effect the outcome of the game are handled by the server and passed to the client, while the non-critical calculations are handled by the client.

In the simplest case you'll be keeping the client in sync with where it expects the server to be, the server will verify, then the client will calculate again.
> 1 votes

---
Tags: ai, mmo, server, movement, npc
---


# Question
Title: Learning OpenGL: Red and Blue book still relevant?
I've recently purchased the Orange book( GLSL ) and am wondering if it is important at all to read through the red and blue books as well?

Any thoughts?

# Answer
GLSL is just the shading language. It doesn't deal with where vertex data comes from, where textures come from, fragment blending, depth testing, the viewport, framebuffer objects, etc. Shaders are important, but they're not everything.

While I'm sure the Orange Book talks about these, as necessary for discussing GLSL, it doesn't go into the detail that other books would.
> 8 votes

# Answer
It seems like the last version of the blue book is from 2007(Open GL 2.1) and the last version of the red book is from 2009 (Open GL 3.0 - 3.1).

The current version of Open GL is 4.1 (Edit: 4.2)

I would try getting my hands on something newer, although knowing legacy Open GL might be useful if you're going to read and maintain old open gl code.

Hope this helps.
> 3 votes

# Answer
I found my first edition (June 1993) copy of the red book (covering OpenGL 1.0) was sufficient and roughly equivalent to GLES 1 on the iPhone. GLSL and OpenGL 3+ are very different (no more fixed pipelines), and I wouldn't bother with the red book unless you need to support GLES 1.
> 2 votes

# Answer
The red book is fine, like others said you can still get value from it for a lot of things, particularly if you ever need to code for embedded and/or downlevel hardware that may not support shaders. Beware though that the free version online is hideously outdated.

I also make occasional use of the blue book, but that's because I like a good reference manual with everything in the one place, and I prefer dead tree to electronic for this kind of thing.
> 2 votes

# Answer
I'd wait to get the red book(if you are going to buy it), a new version is on the way (December?) that covers OpenGL 4.2. The current (7th edition) red book covers both 3.0 and 3.1 and talks about the deprecated fixed function pipeline stuff. The new book will only talk about the current programmable pipeline.

If you really need a book to learn the new OpenGL API the OpenGL Superbible 5th edition is the only book in the series that covers the new OpenGL pipeline (3.1 and higher).
> 2 votes

---
Tags: opengl
---


# Question
Title: XNA 2D Transform Matrix Scale at Zoom Question
This is the complete code I am currently using for my camera. It is incomplete and only partially understood by me (I am working off an example), but I have managed to hack some functionality with some brute force, only to realize I went about it all wrong.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;

namespace _2DCameraPractice
{
  class Camera
  {
    int speed;
    int maxZoom;
    float zoom;
    float rotation;
    bool moveToWorldPoint;
    bool keyPressed;

    Game game;
    GraphicsDevice graphicsDevice;
    Camera camera;
    Matrix matrixTransform;

    Vector2 cameraPosition;
    Vector2 worldPoint;

    KeyboardState currKeyboardState;
    MouseState currMouseState;
    MouseState prevMouseState;

    public Camera(Game game, GraphicsDevice graphicsDevice)
    {
        this.game = game;
        this.graphicsDevice = graphicsDevice;
        zoom = 1;
        maxZoom = 5;
        rotation = 0;
        cameraPosition = Vector2.Zero;
        camera = this;
    }

    public float Zoom
    {
        get { return zoom; }
        // Negative flips image
        set { zoom = value; if (zoom < 0.1f) zoom = 0.1f; }
    }

    public float Rotation
    {
        get { return rotation; }
        set { rotation = value; }
    }

    public Vector2 Position
    {
        get { return cameraPosition; }
        set { cameraPosition = value; }
    }

    Vector2 CamCenterOffset
    {
        get { return new Vector2(game.Window.ClientBounds.Height
            / 2, game.Window.ClientBounds.Width / 2); }
    }

    Vector2 CamCenterInWorld
    {
        get { return cameraPosition + CamCenterOffset; }
    }

    Vector2 MouseCursorInWorld
    {
        get
        {
            currMouseState = Mouse.GetState();
            return cameraPosition + new Vector2(currMouseState.X,
                currMouseState.Y);
        }
    }

    public void Direction(Vector2 direction)
    {
        cameraPosition += direction;
    }

    public Matrix Transform(GraphicsDevice graphicsDevice)
    {
        float ViewportWidth = graphicsDevice.Viewport.Width;
        float ViewportHeight = graphicsDevice.Viewport.Height;

        matrixTransform =
          Matrix.CreateTranslation(new Vector3(-cameraPosition.X, -cameraPosition.Y, 0)) *
              Matrix.CreateRotationZ(Rotation) *
              Matrix.CreateScale(new Vector3(Zoom, Zoom, 0)) *
              Matrix.CreateTranslation(
                    new Vector3(ViewportWidth * 0.5f, ViewportHeight * 0.5f, 0));
        return matrixTransform;
    }

    //Zoom in to mouse cursor.
    private Vector2 ZoomToMouse(Vector2 mousePos, Vector2 cameraPos)
    {

        Vector2 newCamPosition = cameraPos + ((mousePos - CamCenterOffset) / 3);

        //Need to figure a way to center mouse on screen as zooming.

        return newCamPosition;
    }

    private void CenterMouseOnZoom(Vector2 mousePos)
    {
        //The farther from center the cursor is, the more shifts it takes to center
        bool shift = false;
        int X = 0;
        int Y = 0;

        //If the X axis is within 100 units of center, jump once.
        if ( (mousePos.X - CamCenterOffset.X) <= 100
            && (mousePos.X - CamCenterOffset.X) >= -100)
        {
            shift = true;
            X = (int)CamCenterOffset.X;
            //Mouse.SetPosition((int)GetCamCenterInView.X, Y);
        }
        if ((mousePos.Y - CamCenterOffset.Y) <= 100
            && (mousePos.Y - CamCenterOffset.Y) >= -100)
        {
            shift = true;
            Y = (int)CamCenterOffset.Y;
        }
        if(shift)
            Mouse.SetPosition(X, Y);
    }

    public void CameraControlls()
    {
        MouseControl();

        KeyboardControl();
        KeyboardSpecials();

        //Camera special commands
        if (moveToWorldPoint == true)
            CenterCameraOnWorldPoint();

    }

    private void KeyboardSpecials()
    {
        //Output camera and mouse coordinate details.
        if(currKeyboardState.IsKeyDown(Keys.Space))
        {   //Bool check to prevent repeat outputs.
            if(!keyPressed)
            {
                System.Console.WriteLine("Camera : " + cameraPosition);
                System.Console.WriteLine("Zoom   : " + camera.Zoom);
                System.Console.WriteLine("InWorld: " + CamCenterInWorld + "Camera");
                System.Console.WriteLine();
                System.Console.WriteLine("WorldPT: " + worldPoint);
                System.Console.WriteLine("InWOrld: " + MouseCursorInWorld + "Mouse");
                System.Console.WriteLine();
                System.Console.WriteLine();
                keyPressed = true;
            }
        }
        if(currKeyboardState.IsKeyUp(Keys.Space))
            keyPressed = false;
    }

    private void KeyboardControl()
    {
        //Camera movement (Keyboard)
        if(currKeyboardState.IsKeyDown(Keys.Right) || currKeyboardState.IsKeyDown(Keys.A))
        {
            camera.Direction(new Vector2(-(1 * speed), 0));
            moveToWorldPoint = false;
        }

        if(currKeyboardState.IsKeyDown(Keys.Left) || currKeyboardState.IsKeyDown(Keys.D))
        {
            camera.Direction(new Vector2(1 * speed, 0));
            moveToWorldPoint = false;
        }
        if(currKeyboardState.IsKeyDown(Keys.Up) || currKeyboardState.IsKeyDown(Keys.S))
        {
            camera.Direction(new Vector2(0, 1 * speed));
            moveToWorldPoint = false;
        }
        if(currKeyboardState.IsKeyDown(Keys.Down) || currKeyboardState.IsKeyDown(Keys.W))
        {
            camera.Direction(new Vector2(0, -(1 * speed)));
            moveToWorldPoint = false;
        }

        //Camera zoom (Keyboard)
        if(currKeyboardState.IsKeyDown(Keys.Z))
            camera.Zoom += 0.1f;
        if(currKeyboardState.IsKeyDown(Keys.X))
            camera.Zoom -= 0.1f;

        //Camera rotation (Keyboard)
        if(currKeyboardState.IsKeyDown(Keys.C))
            camera.Rotation += 0.1f;
        if(currKeyboardState.IsKeyDown(Keys.V))
            camera.Rotation -= 0.1f;
        if(currKeyboardState.IsKeyDown(Keys.Home))
            camera.Rotation = 0.0f;

        //Speed up scroll when zoomed way out.
        if(camera.Zoom < 0.2)
            speed = 1 + ((1 - (int)camera.Zoom) * 40);
        else if(camera.Zoom < 0.4)
            speed = 1 + ((1 - (int)camera.Zoom) * 20);
        else if(camera.Zoom < 0.7)
            speed = 1 + ((1 - (int)camera.Zoom) * 8);
        else if(camera.Zoom < 1)
            speed = 2 + ((1 - (int)camera.Zoom) * 4);
        else
            speed = 6 - (int)camera.Zoom;
        if(speed < 1)
            speed = 1;

    }

    private void MouseControl()
    {
        Vector2 mousePosition = new Vector2(currMouseState.X, currMouseState.Y);

        //Enable moveTo for world Point on [L.CTRL + L.Click] if mouse is inside
        // window bounds.
        if (currMouseState.LeftButton == ButtonState.Pressed
            && mousePosition.X >= 0 && mousePosition.Y >= 0
            && mousePosition.X <= game.Window.ClientBounds.Width
            && mousePosition.Y <= game.Window.ClientBounds.Height)

        {
            //SetWorldPoint(MouseCursorInWorld);
            SetWorldPoint(MouseCursorInWorld);
        }

        //Enable moveTo for world Point on [L.CTRL + L.Click]
        if(currMouseState.LeftButton == ButtonState.Pressed
            && currKeyboardState.IsKeyDown(Keys.LeftControl))
        //if (currKeyboardState.IsKeyDown(Keys.LeftControl))
        {
            moveToWorldPoint = true;
        }

        //Camera zoom (MouseWheel)
        //Mouse wheel is (up to) ~120 points per click... No shit.
        if(currMouseState.ScrollWheelValue < prevMouseState.ScrollWheelValue)
        {
            //Holding shift while zooming 10+ times more sensative.
            if(currKeyboardState.IsKeyDown(Keys.LeftShift))
            {
                camera.Zoom += (float)((prevMouseState.ScrollWheelValue -
                    currMouseState.ScrollWheelValue) / 10) * 0.001f;
            }
            else
            {
                camera.Zoom -= (float)((prevMouseState.ScrollWheelValue -
                    currMouseState.ScrollWheelValue) / 10) * 0.015f;
            }
        }
        if(currMouseState.ScrollWheelValue > prevMouseState.ScrollWheelValue)
        {
            if(camera.Zoom <= maxZoom)
            {
                if(currKeyboardState.IsKeyDown(Keys.LeftShift))
                {
                    camera.Zoom -= (float)((currMouseState.ScrollWheelValue -
                        prevMouseState.ScrollWheelValue) / 10) * 0.001f;
                }
                else
                {
                    camera.Zoom += (float)((currMouseState.ScrollWheelValue -
                        prevMouseState.ScrollWheelValue) / 10) * 0.015f;

                    //Reposition camera towards cursor durring zoom.
 //                   cameraPosition = ZoomToMouse(mousePosition, cameraPosition);
 //                   CenterMouseOnZoom(mousePosition);
                }
            }
        }
        prevMouseState = currMouseState;

    }

    private void SetWorldPoint(Vector2 worldPoint)
    {
        this.worldPoint = worldPoint;
    }

    private void CenterCameraOnWorldPoint()
    {
        int pixelsLarge = 10;
        int pixelsFine = 1;

        //Shift Left
        if (worldPoint.X < (cameraPosition.X + CamCenterOffset.X)
            && (cameraPosition.X + CamCenterOffset.X) - worldPoint.X > 20)
            cameraPosition.X -= pixelsLarge;
        else
            cameraPosition.X -= pixelsFine;

        //Shift Right
        if (worldPoint.X > (cameraPosition.X + CamCenterOffset.X)
            && worldPoint.X - (cameraPosition.X + CamCenterOffset.X) > 20)
            cameraPosition.X += pixelsLarge;
        else
            cameraPosition.X += pixelsFine;

        //Shift Up
        if(worldPoint.Y < (cameraPosition.Y + CamCenterOffset.Y)
            && (cameraPosition.Y + CamCenterOffset.Y) - worldPoint.Y > 20)
            cameraPosition.Y -= pixelsLarge;
        else
            cameraPosition.Y -= pixelsFine;

        //Shift Down
        if (worldPoint.Y > (cameraPosition.Y + CamCenterOffset.Y)
            && worldPoint.Y - (cameraPosition.Y + CamCenterOffset.Y) > 20)
            cameraPosition.Y += pixelsLarge;
        else
            cameraPosition.Y += pixelsFine;

        if(worldPoint.X - (cameraPosition.X + CamCenterOffset.X) < 5
            && worldPoint.Y - (cameraPosition.Y + CamCenterOffset.Y) < 5)
        {
            moveToWorldPoint = false;
        }
    }

    public void Update(GameTime gameTime)
    {
        currKeyboardState = Keyboard.GetState();
        currMouseState = Mouse.GetState();

        this.CameraControlls();

    }
}

```

}

Essentially what I am trying to do is make a 2D camera with these basic features:

* \[optional\] Zoom out straight, Zoom in towards mouse cursor (centering on it as it goes)
* \[optional\] Hotkey + L.Click, shift view to click location. (Farther zoom = faster shift)
* L.Click, Select world object, at any zoom level.
* WASD & Arrow, view move(s).

As you can see I managed to hack in some very quirky examples of these (have not dome arrow select yet), but they are not working as I expected and I am sure it has to do with the Matrix transform, and my lack of understanding it in code terms. (I have read up on it in many places)

For example. At zoom 1, everything pretty much works, and X,Y coordinates line up with window resolution as it should. But if I zoom in or out, X,Y coordinates do not scale with the new size of the viewable world space. What was once 600x600 pixels is now 60x60 (at zoom 0.1) but clicking in the far bottom right corner, still returns a world vector of ~600x600 rather then the much larger distance.

I have looked for HOURS to find a good explanation on how to code the matrix in XNA, as well as why you would use one of the overloads vs. another. But all I find are simple static JRPG and platformer camera examples. Or first person shooter type cameras.

Now before you answer I hope you will understand when I say that I am a stare and compare learner. If I have a working example of code, with a minimum of explanation, I can infer most of the rest and figure out hat remains by poking it and seeing what happens. So if anyone would be willing to simply adjust the code I have posted WITH VERBOSE COMMENTING, It would help me most. But I will be grateful for any assistance you are willing to give.

# Answer
> 1 votes
I seem to have figured out how to get the coordinates to scale...

I was assuming that the current mouse status would reflect the world matrix its clicked on, but apparently it never actually does this. It is always linked to the view matrix. (The screen itself) and that value needs to scale along with the world matrix (in the transform).

So as the transform is effected by Zoom in the Matrix.CreateScale(new Vector3(Zoom, Zoom, 0)) so too does the mouseState X & Y coordinates need to be scaled by it to virtually mirror the world matrix.

```
    //Offsets any cam location by a zoom scaled window bounds
    Vector2 CamCenterOffset
    {
        get { return new Vector2((game.Window.ClientBounds.Height / Zoom)
             * 0.5f, (game.Window.ClientBounds.Width / Zoom) * 0.5f);
        }
    }

    //Scales the mouse.X and mouse.Y by the same Zoom as everything.
    Vector2 MouseCursorInWorld
    {
        get
        {
            currMouseState = Mouse.GetState();
            return cameraPosition + new Vector2(currMouseState.X / Zoom,
                currMouseState.Y / Zoom);
        }
    }

```

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


# Question
Title: Database structure for a trading cards video game (TCG)
Just started and after pondering with registered users' table everything came to a halt.

So far I've got:

```
+----------------------+
| tblUsers             |
+----------------------+
| userID(primaryKey)   |
| username             |
| password *           |
| accountStatus **     |
+----------------------+

* hashed
** 0=not activated, 1=activated, 2=suspended

```

Still haven't decided on each of the field's data type. But the question is: should I have one big massive table for all the cards or split them into say `tblCreatures`, `tblSpells`, `tblTraps`, `tblQuests` tables?

Plus, for example, some of the creatures have special abilities besides the usual strength and health stats. So I assume if there was `tblCreatures`, it would have `cardTitle`, `cardStrength`, `cardHealth`, `cardDescription` and then it would have `cardAbility0...4`, because I doubt that a single creature card can have more than 2 abilities?

Also how would I contain each user's decks? A single user for example can have up to 10 decks created by themselves, which will be saved on the server.

Any suggestions/remarks?

The project will either be purely written in C# (both client and server) and XNA4, or maybe in the future the client will be ported to Flash+AS3 while server will be done in C#.

# Answer
I'm working on a TCG myself, so I have a little bit of experience with it.

I would have a base "Card" table which would have the columns common to all cards, such as Name, Description, CastingCost or whatever.

Then for each type you'd have the type specific columns which would foreign key to the Card table. The CardId can be both PK and FK in the Creature/Spell/Trap/Quest table.

You can either have an explicit "CardType" column, or you can simply say that if the CardId is in the Creature table, then it's a creature.

As far as decks go, I have a CardInstance table which represents a specific card instance that a user owns, then I have a table called joining table between that and Deck (For lack of a better name, it's Deck\_CardInstance) that represents a card in a specific deck. This allows a specific card instance to be in multiple decks.

You may or may not want this, but if someone wants to share a rare card they own between decks, they're going to do so by swapping which deck the card's in anyway. Might as well make it less annoying for them. The other benefit of this is that a CardInstance may be in no deck. The user hasn't organized it into a deck yet.

In this setup it's assumed that a deck and a card instance belongs to a single user, which seems like a safe assumption.

Below is a database diagram similar to what I'm using but simplified to your example. (For instance I don't know if you just have ability names that match to abilities in code or if you have data-driven abilities stored in the database.)
> 10 votes

# Answer
I'm not familiar with TGC. I assume you trade cards and each card can be categorized into one of four types: tblCreatures, tblSpells, tblTraps, tblQuests

If the four types are very unrelated, then I would split them into four tables, so you can manage each type independently, much like you outlined your tblCreatues. You would need to add a cardID to each of these four tables, and this ID should be unique amongst the four tables (don't use the same ID in more than one table).

You would need a tblDeck, such as:

* deckID
* cardType
* cardID

'cardType' would tell you which of the four card type tables to search in. 'cardID' would be the index into that table. ('cardID' doesn't NEED to be unique like I mentioned above, but it would make things cleaner IMO)

I'd keep your tblUsers much like you outlined, with a unique userID.

Lastly, each user can have multiple decks, so you need a new table to join the two: tblUserDeck:

* userID
* deckID
> 7 votes

# Answer
From a DB programmer passing by...

It depends how different are your items. I think for your case, that you should have a main table, for all main shared fields, and additional specific tables for each specific field.

The main table, must have a special field that indicates what kind of specific table relates that item.

When you read info from the database you read the main table, and later, if applies, bring additional specific info for that card.
> 7 votes

# Answer
There are a bunch of questions there, but I'll just deal with one. I'd recommend making Abilities a different table and making a many-to-many table that connects cards with Abilities. It's common in TCGs to have multiple creatures with the same ability, and Ability0, 1, 2, and so on is sort of clumsy and limits your future options.
> 2 votes

---
Tags: xna, c#, design-patterns, databases
---


# Question
Title: Using SQL for a Realtime Multiplayer Game Server's Working Data (Fast Enough?)
The game I'm working on currently has a Client in Flash AS3, and a Server in C# (multithreaded).

Currently I use mySQL to handle logins (Raw access: no middleman for accessing the database) which seems to be extremely quick.

My question is would using a mySQL database be quick enough for a fairly simple real time game?

My game functions in a similar way to Diablo2, League of Legends, or even Starcraft:

---

1. User logs in
2. User is taken to lobby
3. From lobby user may view active games
4. User's group into 2-8 for games which exist on the server in it's own thread

---

Now, the game has been designed in such a way to minimize server calculations, while still providing zero trust to clients. Is it possible to use SQL in a way to store and manipulate all game data, for each game? ie:

---

1. Users 1 through 8 all create 50 units
2. Each user commands all of their units to move to a location on the map
3. Units attack each other
4. etc.

---

Is SQL fast enough to handle this kind of data traffic? Or would it be better to store it all in memory? Or is there some alternative (such as paging) I haven't considered?

# Answer
> 6 votes
What do you mean by "Raw access"? If it means what I think it means you have got a gaping security hole.

As for the performance question, it would be stupid to try using a database for such a job, for a ballpark figure I'd say an average database is 1000 times slower than memory. Just keep everything in application memory, I don't think you'll run out of memory before you hit some other bottleneck.

# Answer
> 5 votes
Typically, simulation state is kept in memory and the server will send it out to the clients while longer term info like active games and who is connected would be kept in a database that all the services like the lobby can pull info from.

Raw access, direct from the client with SQL commands? Bad idea. Have the server receive requests, which you then internally create the SQL commands from.

# Answer
> 3 votes
I'd have to say it really depends on your game/simulation and how well you can model it in SQL.

Nowadays SQL Servers can keep lots of data 'live' in memory, and optimize access and processing of the data extremely well.

And SQL should scale, in many ways, number of users, servers, processors, memory etc. - Some of this really difficult stuff to do from scratch....

---
Tags: architecture, optimization, client-server, sql
---