# Question
Title: Optimal touch controls for a twin-stick shoot 'em up?
So we recently launched a shoot 'em up arcade-type game (think *Smash TV* or *I Made a Game with Zombies in It!*). You can move in one direction and fire in another, so the ideal control scheme is probably two analog joysticks (like the Xbox 360 has). We support WASD to move and arrow keys to fire. The best way to control though is to move with WASD and aim with the mouse.

We're getting a lot of people asking for mobile versions of the game (mostly for iPad and Android) and the problem is we just can't come up with a good way to translate the controls over to a touch device.

Interestingly, someone actually hacked an early version of our game a while back to work on Android by overlaying D-pads, and sure enough, it was almost impossible to control. The game gets really difficult later on, and the thought of releasing a game with a crappy control scheme that nobody could possibly ever use to beat the game does not sit well with me.

So I was wondering if anyone has any previous experience or suggestions on how to approach this problem? Overlaying two D-pads on the screen is clearly not the way to go and we're kind of at a loss for other ideas.

# Answer
Virtual dual-sticks are just rough on a touch screen.

**Option #1: Movement Stick + Touch to shoot**

Put one virtual stick on screen to control the player. The other finger touches on the screen where you want to shoot. This still gives you one virtual stick to deal with, but moving is often less critical than aiming in this style of game so at least the aim is very precise.

**Option #2: Drag movement + Touch to shoot**

Shoot functions the same as above, just movement is changed.

A finger pressed on the player's avatar and then dragged to a new location sets a waypoint for movement. Players move through the level setting a series of waypoints, setting a new point instantly transitions the player movement. This gets rid of virtual sticks entirely, but depending on your game it might not offer enough fidelity in player control.
> 3 votes

# Answer
For android it might be really hard to implement that control scheme as a lot of devices are not multi-touch.

**For the Ipad/iphone, you could have virtual thumb-sticks on each side of the screen reset their position when the users thumbs/fingers are placed down.**
> 1 votes

# Answer
What if movement was controlled by touch and the shooting was controlled by accelerometer/gyro?

To move, the player would touch the point on screen they want to move to, or the direction they want to move in.

The turn the character around, the player physically would rotate, or they woud turn the device around in their hands.

Obviously there are a lot of situations where this would be unplayable, but it could be fun and unique in the right environment. Definitely the kind of thing that you couldn't do on a non-mobile system. Sometimes things like that can be a big selling point.
> 0 votes

# Answer
Zelda games for Nintendo DS might be useful for inspiration - you hack/slash and shoot by tapping where to attack/shoot, in the general direction or directly on enemies - and then move by holding somewhere on the screen which makes your character start moving towards that point until you stop holding.

* Move: hold down on a point to start moving towards
* Attack: tap on a point to attack

Obviously, you can't walk and shoot at the same time - so it might not work in all situations - but it felt pretty useful with a stylus ^^
> 0 votes

---
Tags: game-design, input, touch, shoot-em-up
---


# Question
Title: Can I load OGRE's mesh file via direct3d?
I just posted this question over at the the OGRE 3D forums, and I wanted to post it here as well.

I'm a newbie here, just found that OGRE is an amazing engine for 3d programming.

Using the Entity class it's easy to load a static model which was exported via some kind of 3ds max plugin.

But I did't read the source-code of OGRE Because I'm not familar with it, and I just got started with OGRE a couple days ago.

So the question is: Does anyone know if I can load a OGRE mesh via d3d?

Or has anyone been doing something using the `OgreEntity.h` and split it out into a separate class which can directly be used in raw direct3d?

I would appreciate if anyone could share some information about the OGRE mesh file format.

# Answer
The easiest way is probably to just export the model in a direct3d compatible format? Or convert the existing `.mesh` file.

If you really want to use the OGRE mesh format and load that outside of OGRE, your best bet would be to write your own deserializer. You could use the MeshSerializer as a starting-point.
> 1 votes

---
Tags: directx, ogre
---


# Question
Title: Can I call c functions within the XNA framework?
I would like to make a 360 game and was just wondering if I could re-use some existing C code I have or whether I need to re-write everything in C#. Any help is appreciated.

# Answer
Yes and no.

Officially, the only thing you can use on the 360 with XNA is C#. You can't ship any unmanaged DLLs with an app on xbox live, and if you want to write your game in C, you need a dev kit and an impossible-to-get contract with Redmond.

That said, anything you can compile into CIL that will run on the compact framework will be okay. If you can convince your code to compile as managed c++, you should be able to get it to work.

**2016 Update**

Times have changed. Grab VC++, your off-the -shelf XBONE and go nuts.

Or, better yet -if you're really stuck on C#, which is a pretty great little language - use Unity, or monogame. The former is a complete, really awesome engine and ecosystem, the latter is perfect if you want to roll your own.
> 12 votes

# Answer
its better to use C#. bacause that using C# will not cause unknow problems.

however, Yes, it can cll C functions.
> -5 votes

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


title: Resume option on game in android

text:
# Question
Title: Resume option on game in android
I made simple puzzle game. I want to add a "Resume" option to it, so when user opens the game, he can pick up where he left off last time.

# Answer
> 3 votes
You'll have to write your current game-state to "disk" whenever the user quits the application or triggers a "save-game" manually. This is also called serialization. Whenever the application resumes, deserialize the data and restore the previous game-state.

The data that is needed for serialization heavily depends on your game.

I'm not an android developer, but I suggest you have a look at the Serializable Interface and the onPause and onResume callbacks.

# Answer
> 1 votes
There are several ways to preserve state in Android apps.

If your gameplay is limited to a single `Activity` (common for anything relying a `SurfaceView`), and your game state is relatively small, you can often rely on the `savedInstanceState Bundle` passed into `Activity.onCreate`. Not only does this allow to to support saved state as the user goes into and out of the game, it will also bullet proof your code against various `Configuration` changes, such as opening the keyboard or changing display mode.

You can also use `SharedPreferences` to store data in one or more key/value maps. This is probably the most common solution, and becomes available to all Activities within your app (and even other entry points, such as `BroadcastReceivers`, in a thread safe manner.

Probably not the best approach for games, other than some deep inventory RPGS, every Android device has an SQL instance built in.

Finally, you have access to the file system. Both in an application private folder accessible by `Context.getDir(..)`, or via the phone's SD Card. The latter will require an additional user privledge, but it is the best route to go if you expect your game state to be large (half a meg or more). Both will require you to get familiar with the `java.io` package, and maybe the `java.nio` package.

If you want state to persist between reinstalls, you'll have to look at setting up backup support for your app, or run a server that can store and retrieve state. I've had good luck with using Google App Engine for network server (for free!).

---
Tags: android
---


# Question
Title: Xna: Splitting one large texture into an array of smaller textures
I would like to split a large texture into a one dimensional array of smaller textures. How should I do this?

# Answer
> 7 votes
Are you talking about 2D or 3D Textures?

When you're drawing 2d graphics with SpriteBatch.Draw(), you have the option to set a source and destination rectangle. To keep track of a collection of smaller textures, you'd have an array/list/whatever of Rectangle objects that represent the source rectangle of your loaded Texture.

See MSDN's documentation for SpriteBatch: http://msdn.microsoft.com/en-us/library/ff433987.aspx

I haven't done any 3D in XNA, but I presume there's a similar mechanism.

# Answer
> 1 votes
Here's a method that should do what you need:

```
    /// <summary>
    /// Splits a texture into an array of smaller textures of the specified size.
    /// </summary>
    /// <param name="original">The texture to be split into smaller textures</param>
    /// <param name="partWidth">The width of each of the smaller textures that will be contained in the returned array.</param>
    /// <param name="partHeight">The height of each of the smaller textures that will be contained in the returned array.</param>
    public Texture2D[] Split(Texture2D original, int partWidth, int partHeight, out int xCount, out int yCount)
    {
        yCount = original.Height / partHeight + (partHeight % original.Height == 0 ? 0 : 1);//The number of textures in each horizontal row
        xCount = original.Height / partHeight + (partHeight % original.Height == 0 ? 0 : 1);//The number of textures in each vertical column
        Texture2D[] r = new Texture2D[xCount * yCount];//Number of parts = (area of original) / (area of each part).
        int dataPerPart = partWidth * partHeight;//Number of pixels in each of the split parts

        //Get the pixel data from the original texture:
        Color[] originalData = new Color[original.Width * original.Height];
        original.GetData<Color>(originalData);

        int index = 0;
        for (int y = 0; y < yCount * partHeight; y += partHeight)
            for (int x = 0; x < xCount * partWidth; x += partWidth)
            {
                //The texture at coordinate {x, y} from the top-left of the original texture
                Texture2D part = new Texture2D(original.GraphicsDevice, partWidth, partHeight);
                //The data for part
                Color[] partData = new Color[dataPerPart];

                //Fill the part data with colors from the original texture
                for (int py = 0; py < partHeight; py++)
                    for (int px = 0; px < partWidth; px++)
                    {
                        int partIndex = px + py * partWidth;
                        //If a part goes outside of the source texture, then fill the overlapping part with Color.Transparent
                        if (y + py >= original.Height || x + px >= original.Width)
                            partData[partIndex] = Color.Transparent;
                        else
                            partData[partIndex] = originalData[(x + px) + (y + py) * original.Width];
                    }

                //Fill the part with the extracted data
                part.SetData<Color>(partData);
                //Stick the part in the return array:
                r[index++] = part;
            }
        //Return the array of parts.
        return r;
    }

```

And here's an example of how to use it:

```
    protected override void LoadContent()
    {
        //Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        Texture2D tex = Content.Load<Texture2D>("MyTexture");
        parts = Split(tex, 10, 10, out xCount, out yCount);
    }

    Texture2D[] parts;
    int
        xCount,
        yCount,
        partWidth = 10;
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin(SpriteSortMode.Texture, BlendState.Opaque);
        for (int y = 0; y < yCount; y++)
            for (int x = 0; x < xCount; x++)
                spriteBatch.Draw(parts[x + y * xCount], new Rectangle(10 + x * 40 + x * 10, 10 + y * 40 + y * 10, 40, 40), Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }

```

Please realize that this is not quite the most efficient way to do what you want, but it is very maintainable and easy to understand (I hope).

If you're looking for more efficiency, and have some experience with XNA, I would recommend using RenderTargets1. Just set each texture "part" in your array as a render target, then draw the original large texture, offset by the position of the part you're drawing. Be aware that this method requires your XNA project to target the Hi-Def profile 99% of the time, which is why I couldn't give you a working sample with that method (my current computer doesn't support the Hi-Def profile). I have used RenderTargets to do this exact thing in the past, though, so it's possible. It's also much easier2 now than in previous versions of XNA, thanks to the RenderTarget changes in XNA Game Studio 4.03.

Please feel free to comment if you need any clarification or more help :)

Links:

1. http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.rendertarget%28v=xnagamestudio.31%29.aspx
2. https://web.archive.org/web/20150920191915/http://blogs.msdn.com/b/shawnhar/archive/2007/02/04/xna-rendertarget-semantics.aspx
3. https://web.archive.org/web/20150919060328/http://blogs.msdn.com/b/shawnhar/archive/2010/03/26/rendertarget-changes-in-xna-game-studio-4-0.aspx

---
Tags: xna, 2d, textures
---


# Question
Title: What do I need to know about game design before I design and develop a game in Silverlight?
I have started to design a game. I have weighed up the options of XNA, Unity, and Silverlight. I am going with Silverlight... Is there anything I important that I am missing that I need to know?

**EDIT**

I sketched the structural design yesterday: http://carnotaurus.tumblr.com/post/4921541502/old-school-game-to-be-written-in-silverlight

Not to repeat the game specifications at great length, a description of the 2D old school game can be found here: What approach would you take to develop an old school game?

# Answer
> 2 votes
I would say you need to know:

* Basics of object-oriented programming
* C# (or VB.NET)
* What you plan to build (graphics engine? physics engine)
* What you *don't* plan to build (eg. what you will look to use existing code for -- like a 2D game engine)
* The game idea
* The core gameplay mechanic

An example of core gameplay mechanic is: in Tetris, you spend 99% of your time rotating and placing blocks on top of other blocks, trying to make lines. *That's* your core gameplay.

Most of this you won't know in detail; the rest, you can figure out along the way.

# Answer
> 2 votes
Your question is still too vague and wide-ranging, which is why you only have one response currently. Perhaps you don't realise that it is vague because you're expecting game development to fit some sort of standard check list, but unfortunately it does not. For example, to take what you've mentioned in your response to ashes999, there is not necessarily a controller involved, nor is there even necessarily an engine involved. And the 'core gameplay mechanic' is just a pithy way of saying 'how does the player play'.

Regarding your Tumblr post, 99% of the stuff you've sketched out there would not be of relevance to a typical game developer. In particular games running in Silverlight would hardly ever need any jQuery and the MVC implementation you have (which looks more like MVP than MVC, really) looks like overkill for what would have originally been quite a simple game implemented with an infinite loop of `get_input/update_data/render_screen` calls.

---
Tags: silverlight
---


# Question
Title: How to create a realistic 2D Role-Playing game collision detection?
I’ve always wanted to create an old-fashionned 2D Role-Playing Game like Star Ocean, Final Fantasy, Sword of Mana and even the “Tales of” series, and I guess a lot of people do. But before even writing a single line of code I did a lot of research, drawing and tryouts.

I've found almost all the answers to my questions but there is a problem I haven’t been able to solve: **How do you create a realistic but yet simple collision detection**, like in the games I named before?

I already know several ways of calculating collision detection, look at the following examples:

None of these satisfy my needs.

* Tile-based collisions are way too simple and suits more a Zelda than a Star Ocean. Plus, the drawing of each tile needs to fill up all space in order to look realistic.
* Pixel-perfect has too many constraints. If your tile has some pixel here and there, the player will most likely get stuck in the midle of nowhere(ie: in some games you get stuck on a 2 pixels width tree root).
* And binary masks uses too much memory and settings imo.

I've read alot of documentation but I never found something that looked good to me. And all my tryouts didn't look close to what I used to play with. So if you have any good links or tutorials on how evolved 2D RPG work please let me know.

# Answer
The N Tutorials may help here. Admittedly, they're for an arcade-style platformer, but they'll work just as well for a top-down view RPG; just don't apply gravity. The premise is testing for collision in a collection of basic shapes -- circles, axis-aligned bounding boxes, lines, points, etcetera.

You then somehow either decorate your world with these (perhaps via a custom level editor), or automatically generate them (fit a closest box or circle) -- or both (default to auto generated box/circle, and allow a designer to tweak).

Where I work, we have done quite a few platformers and some top-down exploration games. We've been doing them since the GBA days. We most often use AABBs for characters and objects, tunable in a sprite editor -- and we go crazy here, allowing a ton of boxes per sprite, some with different purposes. We might have:

* one or more collision boxes, describing the shape of the object for running into things;
* possibly many "attack boxes" that only come into being when you're in the middle of an attack (and animate with the sprite), perhaps even two or three per weapon, depending;
* a few "vulnerable boxes" that will take damage when hit by others' attack boxes -- by default, we use the collision box, but the vulnerable boxes tend to feel better when they're smaller than the collision box, and we can allow for location-aware damage this way
* one or more "activation box" on AI that describes the sense region for the AI -- they'll attack if the player is in this region, for example.

The levels are mostly strings of line segments; we have a bit of metadata per segment to describe damaging or slippery surfaces, etc.

So most of the collision detection and response becomes AABB-vs-AABB or AABB-vs-segment. Occasionally we toss in a circle-vs-something for a projectile, although often an AABB will do here as well.

You don't need a lot of basic shapes to make things look good and behave well -- a few will do, provided you can tweak and iterate on them.

---

Also, don't feel bad about blending systems together; tile-based collision may be excellent in some areas (representing the majority of your world) but horrible for object-object interactions. That's fine; use a different system for object-vs-object! Writing for interactions between the two systems may be easier than you think.
> 9 votes

---
Tags: collision-detection, rpg
---


# Question
Title: How do I calculate an offset from an Object based on the Objects Rotation rather than the World Space
I have a Matrix of a player & I want to create a second location a set distance away from the first location but I want the second matrix to be set a set distance based on the rotation of the first matrix e.g. A player looking in a certain direction fires a gun, I want the bullet to start it's existence out side of the players mesh but in the direction the player is facing.

I've uploaded a video of what's happening: http://www.youtube.com/watch?v=9aThUZ94Edo

Ideally I would like to just apply the players rotation Matrix to the Offset amount to get the proper offset Matrix, based in the world space co-ordinates to then be able to apply back to the object.

It's obvious at the end of the video that it's wrong when I am able to shoot the player model from his bullet :-)

# Answer
Assuming the player is facing in its Matrix's Forward direction, this will do what your asking:

```
Matrix secondMatrix = firstMatrix;
SecondMatrix.Translation += (secondMatrix.Forward * zOffset) + (secondMatrix.Up * yOffset);

```

Where zOffset represents the distance in front of the model that you want the bullet to start out from, & yOffset represents the height above gun center you want the bullet to start out from.

The 2ndMatrix takes on the rotation of the 1stMatrix but adds location offsets using the local space vectors to achieve your set distance. You could add barrel elevation rotation to the 2ndMatrix if you wanted.
> 1 votes

# Answer
I'm assuming that your matrices are in row-major form, if not, read column for row.

It's supposed to be a general answer for all orientation-matrices, rather than only for XNA, giving some background about matrices and what data they actually store.

The matrix has the following information:

* 1st Row: The Right-Vector
* 2nd Row: The Up-Vector
* 3rd Row: The Forward-Vector

Now if you want to shoot a bullet in the direction the character is facing, just use the 3rd row (the Forward Vector), scale it by the start-distance from the character and add that to the character's position:

```
bullet_start_pos = player_start_pos + orientation[2] * start_distance;

```

orientation\[2\] is the vector in the 3rd row of the orientation-matrix
> 2 votes

---
Tags: xna, 3d, matrix, sunburn
---


title: Implementing network smoothing

text:
# Question
Title: Implementing network smoothing
We are making a multipler first person shooter. The client sends it's position to the server at a fixed rate (currently at 10Hz). The server sends a single message contatining all player's positions to all players at the same rate (10Hz).

As expected, the movement is pretty choppy since the 60fps game is only recieving updates 10 times a second. What is the best way to smooth this movement? The most obvious way would be to interpolate between the last two packets, so that the interpolation finishes as we recieve a new packet. But this adds an instant 100ms delay for all players.

The other way would be to use the velocity and acceleration inferred from the last few packets to predict where the player is before the next packet arrives, however if the prediction is wrong, the player would tend to jump as soon as a new packet is recieved.

Does anyone know how AAA titles solve this problem?

# Answer
> 9 votes
They do exactly what you've just said - either one of those two approaches, or some compromise between them. (eg. accept a small delay and interpolate where possible, and extrapolate when the ping exceeds that delay.) Instead of jumping (also known as 'snapping') back to a corrected position, you typically do some sort of interpolation between the wrong prediction and the corrected value, smoothing it out, if possible. You also handle the corrections in the past to reduce the amount of correction you need to apply.

This is a frequently asked question and there are several canonical links which you will probably find elsewhere on gamedev.stackexchange.com if you search, and they include the following:

What every programmer needs to know about game networking (this summarises stuff in the next two links)

Source Multiplayer Networking

Unreal Networking Architecture

---
Tags: networking, first-person-shooter
---


title: How do I pause an XNA game?

text:
# Question
Title: How do I pause an XNA game?
I'm trying to implement *pausing* by following this tutorial. The tutorial recommends essentially this as the implementation:

```
if (!paused) {
    Simulate(gameTime);
}

```

How does this work? What does `Simulate` mean here?

# Answer
It's just a simple way to wrap your entire `Update` method in a conditional, without mixing the pausing logic with your game's updating logic.

So instead of:

```
protected override void Update(GameTime gameTime)
{
    if(!paused)
    {
        // Lots and lots of code!
    }
}

```

You can have:

```
private void Simulate(GameTime gameTime)
{
    // Lots and lots of code!
}

protected override void Update(GameTime gameTime)
{
    if(!paused)
    {
        Simulate(gameTime);
    }
}

```

Of course, if you would prefer to express it as "continue the game like normal", you could also do this:

```
protected override void Update(GameTime gameTime)
{
    if(paused)
        return;

    // Lots and lots of code!
}

```

These all do the same thing. Which method you choose to do it is simply a matter of taste. Basically what the tutorial is telling you is:

* Determine if your game should be paused and store that in a variable (ie: `bool paused`)
* If it is paused, *skip over* the code that is responsible for updating your game's state (essentially freezing it in time, ie: "pausing" it.)
> 12 votes

# Answer
As Andrew mentioned, you can simply add a flag in the `Update` loop to check the game's state. However, if your game is a bit more complex, you might want to take a look at the Game State Management code sample, that demonstrates multiple screens, transitions and a pause menu.
> 3 votes

---
Tags: xna, pausing
---


title: Implementing Positional Sound

text:
# Question
Title: Implementing Positional Sound
I am trying to put 3Dish audio in a game I'm developing, and I'm unsure how to do positional sound. I want to be able to adjust the volume of the audio's channels depending on how far it is and the orientation.

# Answer
Since you didn't mention any API for sound I'll give you the general answer.

First get the distance between the audio listener and the audio source
d(L,S) = sqrt((x2-x1)2 \+ (y2-y1)2 \+ (z2-z1)2)

Then you define a distance where you don't want it to be audible anymore, lets say 150m

If your distance is 40 meters from the source, then the volume is about 73%.

To give you an equation that would be:
1-(d(L,S)/maxDistance)
or (1-(40/150)) = about .73
That will be the percentage of volume from 1 to 100%

That's assuming you want the volume to change linearly with your position change.
> 10 votes

---
Tags: 3d, flash, audio, sound-effects
---


title: Rotate spritesheet graphics in flixel

text:
# Question
Title: Rotate spritesheet graphics in flixel
I am using the flash flixel engine, and have a sprite sheet of a spaceship from top-down view. The sprite sheet includes a bunch of different states and animation frames. Problem is that I have drawn them all facing upwards (north), and my maths is all done assuming the sprites face to the right (east).

In flixel v2.5 is there a way to rotate the sprite graphics without affecting the "angle" property of the FlxSprite that is using the graphics? I was thinking along the lines of a pre-process, as I initialise everything. I don't really want to fix all the graphics, or hack into my maths at this point. This also might come in handy later.

# Answer
If you really want to do this in code (instead of converting the sprite-sheets you have), I suggest you use the BitmapData:draw method to draw an existing BitmapData object (your Sprite) into another. When using the `draw` method you can also supply a transform matrix to use, so basically you do the following:

* Create a new BitmapData object with the same size as your sprite (actually, width becomes height and height becomes width).
* Copy your sprite using a 90 degree rotation matrix
* Use the new BitmapData object for the graphics in Flixel...
> 3 votes

# Answer
Look at the command line tool for ImageMagick. It allows you to do batch processing on images, including transforms such as rotation. It's also useful for generating simple spritesheets (not the "packed" kind, but the kind where each the image is cut up into frames of equal width and height).
> 2 votes

---
Tags: flash, actionscript-3, spritesheet, flixel
---


title: Client server design question

text:
# Question
Title: Client server design question
I'm working on creating a multiplayer game, with the client in ActionScript and the server written in Java. I'm using `XMLSocket` in the client to connect to the server. The server code looks something like:

```
ServerSocket server = new ServerSocket(port);

while(true)
{
    Socket client = server.accept();
    ClientHandlingProcess child = new ClientHandlingProcess(client);
    child.start(); // starts new thread for client
}

```

The client handling process looks something like:

```
while(true)
{
    byte[] arr = new byte[1024];
    if(socket.getInputStream().read(arr) == -1)
    {
        break;
    }

    handleInputMethod(arr);

    while(!message_queue.isEmpty())
    {
        socket.getOutputStream().write(message_queue.get(0).getBytes());
        message_queue.remove(0);
    }
}

```

The issue is that the `read` method is blocking, meaning I can't send any data while I'm waiting for data to come in. What would be a good way to fix this? Have two processes: one for reading and one for writing, have the client send empty requests when it has no proper messages to send, or is there another way I can proceed?

# Answer
You have basically these two options:

* Use blocking IO with one reading thread per client
* Use non blocking IO

The first option has the disadvantage that it does not scale for large number of clients.

While non blocking IO can be done by checking inputstream.available(), it may be a good idea to look at the New I/O API. Wikipedia has a good article on NIO with sample code. You can find additional information in the JavaDoc for the NIO package. And on a quick glance this tutorial seems helpful.

You might get away with doing smart things on the client side, such as sending a dummy message on every "turn". This, however, means that a rouge client can freeze your server. So you should not go into this direction.
> 2 votes

# Answer
Never rely on a client to do ANYTHING to make your server run properly. If you do, then malicious users can attack your game simply by refusing to perform whatever is required of them.

Use non-blocking IO or threads for this task. Threads is fine if you have a small number of players (eg, \< 10) and you are confident with passing data safely between threads. Otherwise, go for the non-blocking IO route.
> 2 votes

# Answer
Java's NIO package (as of Java6), provides support for non-blocking I/O only, via Selectors.
> 1 votes

# Answer
I agree with the other answers that NIO provides better results. However using NIO isn't that trivial. You will definitely learn something when you code the NIO network code yourself. Or you just use an asynch network package like netty or Apache Mina. I prefer netty, since I find it better documented. However if you understand one of them, you understand the other one as well.

But, if you want to keep the design you have, you can split the sending and receiving code. Create some "PlayerSession" or "PlayerConnection" Object that provides the methods for sending messages to the client and contains one thread that blocks on the read and handles input. Maybe you want to move the sending stuff to an own thread, just try it.
> 0 votes

---
Tags: java, actionscript-3, networking, server, client-server
---


# Question
Title: Getting error GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT
I am getting error code GL\_FRAMEBUFFER\_INCOMPLETE\_ATTACHMENT when creating framebuffer on Mac (using glCheckFramebufferStatus).

I am using same code for rendering on Mac and iOS both. Maybe problem is in the buffers initialization. On iOS I am doing it this way:

```
    CAEAGLLayer* eaglLayer = (CAEAGLLayer*) super.layer;
    eaglLayer.opaque = YES;

    EAGLRenderingAPI api = kEAGLRenderingAPIOpenGLES2;
    m_context = [[EAGLContext alloc] initWithAPI:api];

    if (!m_context) {
        [self release];
        return nil;
    }

    if (!m_context || ![EAGLContext setCurrentContext:m_context]) {
        [self release];
        return nil;
    }

    [self layoutIfNeeded];

    NSLog(@"Using OpenGL ES 2.0");

    [m_context
        renderbufferStorage:GL_RENDERBUFFER
        fromDrawable: eaglLayer];

```

Variable `m_context` is object `EAGLContext`

On the Mac this way:

```
NSOpenGLPixelFormat *nsglFormat;

NSOpenGLPixelFormatAttribute attr[] =
{
    NSOpenGLPFADoubleBuffer,
    NSOpenGLPFAAccelerated,
    NSOpenGLPFAColorSize, m_colorBits, //16
    NSOpenGLPFADepthSize, m_depthBits, //16
    0
};

[self setPostsFrameChangedNotifications: YES];

///< Next, initialize the NSOpenGLPixelFormat itself
nsglFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attr];

///< Check for errors in the creation of the NSOpenGLPixelFormat
if(!nsglFormat) {
    NSLog(@"Invalid format... terminating.");
    return nil;
}

///< Now create the the CocoaGL instance, using initial frame and the NSOpenGLPixelFormat
self = [super initWithFrame:frame pixelFormat:nsglFormat];
[nsglFormat release];

///< If there was an error, we again should probably send an error message to the user
if(!self) {
    NSLog(@"Self not created... terminating.");
    return nil;
}

///< Now  set this context to the current context

[[self openGLContext] makeCurrentContext];

```

Maybe I am doing anything wrong when I initialize NSOpenGLContext. Can you see any error? Thankyou **UPDATE**: Initialization of the OpenGL I am doing this way:

```
int m_width, m_height;

glGetRenderbufferParameteriv(GL_RENDERBUFFER,
                             GL_RENDERBUFFER_WIDTH, &m_width);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
                             GL_RENDERBUFFER_HEIGHT, &m_height);

// Create the depth buffer.
glGenRenderbuffers(1, &m_depthRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, m_depthRenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER,
                      GL_DEPTH_COMPONENT16,
                      m_width,
                      m_height);

// Create the framebuffer object; attach the depth and color buffers.
glGenFramebuffers(1, &m_framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER,
                          GL_COLOR_ATTACHMENT0,
                          GL_RENDERBUFFER,
                          m_colorRenderbuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER,
                          GL_DEPTH_ATTACHMENT,
                          GL_RENDERBUFFER,
                          m_depthRenderbuffer);

// Bind the color buffer for rendering.
glBindRenderbuffer(GL_RENDERBUFFER, m_colorRenderbuffer);

// Set up some GL state.
glViewport(0, 0, 640, 480);
glEnable(GL_DEPTH_TEST);

```

# Answer
> -1 votes
Finally I have found the solution. It is necessary NOT to use renderbuffer. So I have to DELETE code to init renderbuffer.

# Answer
> 0 votes
I had the exact same problem when I tried adding a depth buffer to the sample code generated by XCode. You should add code to check for framebuffer completion:

```
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    NSLog(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatus(GL_FRAMEBUFFER));
// also check glGetError() here

```

I'm not a Mac expert, but I do remember that the position of the following call is very important:

```
[m_context renderbufferStorage:GL_RENDERBUFFER fromDrawable: eaglLayer];

```

On iOS it needs to be before creating the color and depth components of the framebuffer.

Here is my working iOS code:

```
[EAGLContext setCurrentContext:context];

glGenFramebuffers(1, &frameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);

glGenRenderbuffers(1, &colorRenderBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, colorRenderBuffer);
[context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer *)self.layer];
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderBuffer);

glGenRenderbuffers(1, &depthRenderBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, depthRenderBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderBuffer);

if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    NSLog(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatus(GL_FRAMEBUFFER));

CheckOpenGLError();

```

---
Tags: opengl, macos
---


# Question
Title: What research areas exist in game programming?
I'm currently in a group that researches network optimizations and various distributed applications, I'm much more interested in games but more from a research side.Is there a resource that focuses on research topics specific to game development and what are some common areas of research?

Note:I understand game development is made up of various topics that are thoroughly researched, my question is more geared towards the areas that are exclusive to gaming applications or at least only important for gaming.

One example could be maybe a "genetic algorithm approach to character skill progression". Which would focus on building a skill progression that is most optimal to player returns. Etc etc...Random idea, but you get my point. I also mean the technical side of development too, but I didn't want to limit this.

# Answer
> 9 votes
The primary resources (barring conferences) for research around game development that I've found is the Game Programming Gems books, GPU Gems and the AI Game Programming Wisdom books (Both can be found here).

Both series' feature articles from game developers as well as researchers and at the end of each article they offer a comprehensive reference list to further your understanding on the topic.

EDIT: Although the AI series has ended, they do have some great articles in there, well worth a look.

I would say that the main research efforts are focused on either graphics or AI, probably because they're pretty large areas of interest for academia in general.

The GDC Vault (found on the sidebar of this site sometimes) is also very useful as is GDC itself. Conferences are probably the way to go to keep on the cutting edge of research topics as well as networking to find out what some people are working on, etc.

A great conference for graphics is SIGGRAPH.

Good ones for AI: AIIDE and T-CIAIG.

If you don't have access to the conferences, you could always purchase the proceedings that have all presented papers and articles of interest within them.

A fairly old resource for finding game development research topics is Red3D. It's fairly outdated and a lot of links are broken, but with some Googling of the research areas you should be able to find them again pretty quickly.

Although not official (from an academic perspective), GameDev.net has a good few interesting articles on latest advances as does GamaSutra.

Alex J. Champandard runs AIGameDev and they have a lot of guest speakers, research students, articles, papers, etc. It's pretty comprehensive, but to really get the most out of it you need to be a Premium member which can be a bit pricy.

Hope that helps.

---
Tags: software-engineering, assets
---


# Question
Title: Writing C# for iPhone 2D Game Dev - Not Unity
**What are my options for writing C# code to produce a 2D iPhone game?**

I specifically mention 2D -- Unity will not suffice for me (even though it can "fake" it with a 2.5D game).

I like C# because of language features (LINQ, garbage collection, generic collections, etc.) although I would be open to considering Java as well if nothing exists. Objective C is not my cup of tea.

And **I don't own a Mac.** Eek.

# Answer
I believe part of the strategy from Apple is that you OWN a Mac if you want to become a developer. I haven't checked the latest articles/details regarding their licensing system, but I know that Adobe is now able to ship Flash Builder 4.5 which generates code for the iPhone. I wonder if you still need a Mac to upload it to iTunes.

Xcode, the developer tool from Apple for iOS is Mac only.

There is another approach I've been told though. If you have a spare PC or harddrive, you can buy the original Mac OSX DVD (actually rather cheap last time I checked) and then with a lot of tweaking and researching, you can install Mac OSX ontop of PC hardware and have a dual boot machine.

Look on google for "hackintosh". Its not every PC that will work with this, but search, read and try - it ought to be possible. I am not sure what Apple thinks about this, but if you start by buying the original Mac OSX instead of using a pirated copy, I believe you should be "okay" - cant promise you anything, but thats what I've been told by someone who did it himself.
> 3 votes

# Answer
You can use MonoTouch and write your own GL code, but it isn't nearly as fast to get something up and running as using Unity.

http://forums.monotouch.net/yaf\_postst1420.aspx
> 1 votes

# Answer
I would actually say unity is a very valid tool to accomplish this. You can create both 2.5d and full 2d games using unity. If you change the camera from perspective to orthogonal projection then you are eliminating the depth side of the rendering. Doing this, and using either textured 2d planes or gui textures, you can create a very detailed 2d game. As such, you are no longer limited by the engine to create 2d games. With that said, if you want to develop a full game before porting to IOS, unity is IMO the best route as it lets you develop and partially test without a mac. All other tools I've seen for this are mac only.
> 0 votes

---
Tags: c#, 2d, iphone
---


title: Choosing an engine for a new game

text:
# Question
Title: Choosing an engine for a new game
Right now, I'm planning a new FPS single-player Half-Life 2/Call of Duty: Black Ops/Crysis 2-like, and I'm trying to determine what game engine should I use. Right now, my team is me, as a programmer, and **only one** models/textures artist, so each model takes us a lot of time.

I thought about:

* Source Engine - because it has a lot of existing content I can use to write my game much more quickly. The main disadvantage of Source is that it lacks in the graphics area (especially in vegetation).
* Unity - the ability to use C#, which is my favourite programming language. It is perfect when it comes to graphics, but it doesn't have so much existing content like Source. Plus, it is cross platform.

I also thought about some open source game engines, but most of them (Ogre3D, for example) lacks in development speed and some graphics capabilities.

If there was some model/textures/sound repository (not necessarily free, but also not really expensive), I'd use Unity.

UDK is not an option, as it doesn't give me access to native code and I'll need to use some libraries wrriten in C++.

Are there any more advantages/disadvantages to each engine? Feel free to suggest new game engines. Also, in your opinion, what game engine should I use? Do you know some content repository I can use?

# Answer
> 12 votes
It sounds like you know the pros and cons here. If it's between unity and source and it's just you, simplification is important for development time, and you want a large amount of support, Unity would be the choice I'de make.

Unity does have an asset store to buy from by the way. Unity also lets you use c++ extensions so you can actually use c++ with your code, but again if it's just you, avoid it! I spent 2 months making a puzzle game with two other programmers with unity and we took every shortcut we could given our deadline. If we tried that project in source it would have taken a bit longer as we didn't have to manage our scene or any of the resources.

I don't know your experience level, but if it leans on the side of beginner/intermediate or if you have no other help there's almost no choice here. In my experience, development time in source is much longer than in Unity.

# Answer
> 2 votes
I would take a look at Garage Games Torque-3D engine. They have a very good community, some great resources you can buy to use in your games as well, if aren't making your own content from scratch.

---
Tags: unity
---


# Question
Title: XNA / WP7 accelerometer sample / example ball rolling
Does anyone know of a good WP7 accelerometer sample of a ball rolling around on a screen?

# Answer
Sort of what you want, been a while since I've used samples like this but it should work. http://faculty.washington.edu/ksung/pub/WP7/3.Accelerometer/Accelerometer.html

Just googled "wp7 accelerometer sample". I'de avoid copying the source though. Look more at what you logically want to do and look specifically at the API documentation for XNA to accomplish it. If you want to roll a ball, look up how to add torque to rigidbodies in XNA, then how to get the x and y values from the accelerometer. Apply those to the torque and there ya go!
> 2 votes

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


title: Rendering 2D grass

text:
# Question
Title: Rendering 2D grass
My current project, using Java and OpenGL, has a fairly standard overhead tilemap in the style of the Zelda games.

I'd really like to add "real" grass to the grass tiles so that there are actually blades that can sway in the wind and maybe, if possible, react to the player's movement as well. I'm figuring that since this is only in 2D, a rather striking effect should be possible without much performance hit.

What possible algorithms are there for rendering dynamic 2D grass? If possible, I'd like to keep the effect strictly 2D--i.e., I don't want to render actually 3D grass, as it would break the artistic design of the world.

# Answer
I would make an animation sprite map for the grass. This way you can apply a scene wide call (atleast all visible grass in the scene) to have them randomly go through their animation to make it look like the wind sparsely gusts through the scene. Just have a loopable animation setup for the grass and play them at different speeds and randomly to get the effect. You can also use this to interact with the player by determining which way the player is walking over the grass and play the animation in that direction. This is definitely a high level answer and would require a bit of figuring out to completely hash this idea out.

You could even save on space if you want to. Have a middle position that the grass sits straight up. Have a blowing to the right animation. Then if you want it to blow to the left, smoothly move the animation towards the center and flip the sprite then play the same animation.
> 6 votes

---
Tags: opengl, 2d, graphics-programming
---


# Question
Title: How on earth do you get decent color out of 2BPP?
I've been looking into PowerVR textures, and have run into several textures that are apparently 2 bits per-pixel. This, frankly, boggles my mind. How does one get even half way decent color preservation when you only have 4 possible states per pi per pixel? I would love any resources out there that talk about the compression behind such a feat. Thanks!

# Answer
> 13 votes
PVRTC 2BPP encoding, as introduced in this paper divides an image into 8x4-texel blocks, and compresses each block such that only two RGB colors are stored for each thirty-two texel block.

None of the thirty-two texels stores a color of its own - each texel stores only information about how to blend between the two RGB colors of its 8x4-texel block.

If the source image has an 8x4 texel block with a rainbow of 32 colors in it, PVRTC 2BPP compression will do a very poor job of maintaining its quality, because in PVRTC 2BPP each 8x4 texel block has only two RGB colors to blend with.

# Answer
> 6 votes
Texture compression does not compress pixels. It compresses blocks of pixels. When an individual pixel is referenced, the GPU computes which block represents the pixel. Then it processes the whole block to get the color of that pixel.

An example

Lets assume the block size is 4x4 pixels on an RGB texture. Uncompressed, each block consumes `4x4x3 = 48` bytes in texture memory.
Now the compression algorithm will calculate the average for each channel (RGB) and store it with the block ( 3 bytes). Now lets give each pixel 2 bits to adjust the average so that the pixel is closer to its original color. Thats another `4x4x2x3/8 = 12` bytes.
The total bytes used by this newly invented compressor is 15 bytes per block, a compression ratio of 31.25%.

My mythical compressor uses 7.5 bpp. That isn't as good as the 2 bpp pvrtc can achieve, but now you have rough idea on how 2 bbp might be achieved.

**update:**
I just looked at the wikipedia page for pvrtc. It looks like pvrtc doesn't use traditional block based compression. Here is paper that describes the way block based compression works and how pvrtc differs. Of particular note: Block based filters can produce decent looking images using 4bpp (no alpha), whereas nvrtc can do so with 2bpp.

# Answer
> 1 votes
@Toji, the site the paper is on is a bit temperamental but it worked for me this morning. Failing that, if you have access to ACM/SIGGRAPH, it's hosted here. Strangely, it *was* also on the IMG/PowerVR developer website (free registration) but I can't seem to find the right section. :-(

\[UPDATE\] It is still on the IMG site here\[/UPDATE\]

@bmcnet: PVRTC does not break the texture into blocks like, say, ETC or S3TC. FWIW, I did experiment with block-based textures but I couldn't find a way to pack enough data into self-contained blocks and still get the results I wanted. Instead, it's a bit more of a 'global' texture compression system. It has 2 low resolution images which it bilinearly upscales to the target res, and then mixes these together on a texel-by-texel basis.

---
Tags: textures, compression
---


title: Implementing a tile-based game

text:
# Question
Title: Implementing a tile-based game
Which data structure should be best used to store a pile of tiles from which a player can pick a random tile?

# Answer
> 3 votes
I'd suggest any container that has random access (wikipedia), for example a plain array, vector, or deque.

```
int tiles[100];

```

or

```
std::vector<int> tiles;

```

This will allow you to select a random element without having to step through the container.

*I have left a comment asking for more information, if more information is added I'll update this answer.*

---
Tags: c++, tiles, data-structure
---


# Question
Title: How much time it will take to learn 3ds Max
I am not a 3d developer but i want to lean 3ds max just for simple house building with 2-3 rooms. Actually i don't want to develop from scratch .

What i really want to do is get the existing models of homes , rooms , hotels from the internet and add my name there or my photo there , just for fun .

SO i want to know that how much time do u think it will take me to that sort of stuff.

Its not my career but just hobby . If its going to take longer time , then i don't want to waste but i can get going in one week or so that will go good but i want to ask from experience developers

thanks

# Answer
The problem is you need to learn more stuff about the general UI, and some basic 3D concepts. Only for that which you say, yes, a week if you are smart, dedicate time to it, etc. Two weeks I'd say. But uvmapping and texturing alone has its issues. Max has one of easiest GUIs for newcomers (more arguable if it being the most functional later on)

For modeling, not texturing, Google Sketchup is really great and easy, but the problem is the mesh export.

Another easy one for newcomers is Cinema4D. And a totally free one which would allow this mesh modifying matter, Blender.
> 1 votes

---
Tags: 3dsmax
---


# Question
Title: Library to load images into textures, Linux, C and OpenGl
I am looking for simple, self-contained C library for Linux to load images from files into OpenGL textures. The licence should be quite liberal: zlib, bsd, mit or something. I have found SOIL, however it hasn't been updated for a long time. Is there something else, or do I have to write my own?

P.S. I use glfw. There are only deprecated functions for loading images.

# Answer
I use STB Image for most image loading. A small self contained no strings attached implementation of png and other file formats.
> 5 votes

# Answer
SOIL works great. Who cares if it hasn't been updated in a "long time"? That just means it's stable and well-understood.

(It actually was updated in 2008, which is not long ago at all.)
> 11 votes

# Answer
Check out FreeImage. It's dual-licensed, you may choose either GPL or the liberal FreeImage license. It supports far more image formats than SOIL and development is active.

The library itself is written in C++, but it has an ANSI C interface.

From its introduction:

> Thanks to it's ANSI C interface, FreeImage is usable in many languages including C, C++, VB, C#, Delphi, Java and also in common scripting languages such as Perl, Python, PHP, TCL or Ruby.
> 2 votes

# Answer
Have a look at DevIL.
> 2 votes

# Answer
If you don't need to read many formats, consider writing your own loader code. I use libjpeg and libpng directly and they're quite easy to use. Both have very simple functions that essentially fetch a scanline of RGBA data, just put that into an array and then upload to OpenGL. Both have very useful and straightforward example programs.

I have no experience with other formats, though. But to be honest, PNG+JPEG cover 100% of our needs (which aren't trivial nor hobbyist level - see http://www.mysterystudio.com)
> 1 votes

# Answer
Silly is produced the the CEGUI guys.

I supports loading PNG, TGA, JPG, etc. And it's released with an MIT license.

You'd have to write a C wrapper yourself as the library is written in C++.
> 0 votes

---
Tags: opengl, textures, c, loading, linux
---


# Question
Title: Slow performance on an A* implementation in a tower defense game
I'm making a Tower Defense game in Flash with no predefined path.

Although my grid is 40x40 (small?), A\* is struggling when recalculating every time. So I made my own modification to ease the recalculation and the touched cell count dropped to around 900 (when modifying near the root). It still freezes for a very short, but detectable, amount of time when a new tower is placed.

Is this an implementation problem, or is 40x40 just too much?

**Edit:**

The structure of my code:

* All the data is saved in 2d array of cells.
* Each cell contains its parent in path direction (1-8 clockwise) and bitwise encoded array of its children in path (every bit represents a child).
* The search is performed by A\* with the estimate of euclidian distance.

# Answer
> 4 votes
I can't comment, but first profile in Flex, everything else is conjecture.

# Answer
> 13 votes
*I'm assuming that TD is 'Tower Defence'*

I think A\* is going somewhat overboard for this.

At the start of the game, flood fill the game area from the exit points to create a movement map:

```
 |---------|
 |5|4|3|3|3|
 |5|4|3|2|2|
->5|4|3|2|1->
 |5|4|3|2|2|
 |5|4|3|3|3|
 |---------|

```

and movement is always towards a square with a lower value.

When the player places a tower, update each of the eight adjacent squares: for each square, set it's movement value to one more than the lowest adjacent value. If the value changes, repeat the process centred on the updated square. Then, to check that the route to the exit is not blocked, ensure all squares are adjacent to a square of a lower value.

When the player removes a tower, set the movement value to one more than the lowest adjacent square and repeat the process above.

A simpler approach would be to re-do the flood fill.

# Answer
> 2 votes
Strange, I thought I replied to this, but the reply seems to be gone. Make your search algorithm such that it can be updated in multiple steps, so that when you place a tower and play an animation, you can do a little bit every frame and you'll have somewhere between half a second and a second to update your A\* without a noticable pause. It's latency - iF you can't speed it up, find a way to hide it. Playing an animation while placing a tower would be natural for a game and imo a good place to hide it.

# Answer
> 0 votes
For a start you could change your array to a vector - should give you some speed improvements. Post the code and we might be able to suggest more optimisations.

# Answer
> 0 votes
I would guess that your slowdown is because you are calculating a path for all characters simultaneously. Calculating a path for one character is fast but if there are two dozen characters in the scene then that can bog down.

Instead you should spread out the load over a few frames. Stagger your AI updates so different characters update their path on different frames. It would be really noticeable if a character didn't react until a second later, but just one frame is not going to cause bad reactions.

---
Tags: flash, algorithm, path-finding, tower-defense
---


title: OpenGL ES on iOS Books

text:
# Question
Title: OpenGL ES on iOS Books
I was wondering if someone has read both the:

iPhone 3D Programming

And

OpenGL ES 2.0

books and have an opinion if one is better than the other?

I'm basically wanting to get into doing 3D graphics on iOS including shaders.

# Answer
iPhone 3D programming is a better starter, it's written like a tutorial and in general is better suited for your game development needs. OpenGL ES 2.0 on the other hand goes quite near to the metal, it's more like OpenGL ES 2.0 reference on steroids.

iPhone 3D programming is freely available through O'Reillys OFP system, so you can buy the other one and eventually read both.
> 3 votes

# Answer
iPhone 3D Programming covers both ES 1.1 and ES 2.0. I found that slightly confusing when going through examples but it is up to your preference whether you are interested in 1.1 as well.
> 0 votes

---
Tags: 3d, opengl-es, books, ios
---


# Question
Title: Middleware to Bring 3D Meshes into OpenGL ES 2.0
Say I develop a game for mobile platform running OpenGL ES 2.0. I have done 2D part, and now I wish to import some 3D objects.

The imported 3D objects must contain the following:

* Vertices positions
* Normals
* UVs
* Texturing information
* Animation information
* Collision mesh
* Maybe some other things...

I am aware, that I could and (maybe should) create my own file format that brings these data from 3D authoring application (3ds Max, Maya, Softimage) into the game.

However, doing so from scratch is going to be really be a lot of work. Therefore, is there any available solution/middleware, that will let me import 3d meshes into my game, ready to use?

The solution/middleware should be:

* easy to use
* easy to port
* efficient
* not consuming too much memory with unnecessary things
* containing all the above mentioned features plus things I haven't considered yet

Programming language is: C++.

Currently, I'm developing under Windows 7, Visual Studio 2010, and OpenGL ES 2.0 emulator.

Later, the product will be ported to iOS and possibly Android.

# Answer
> 7 votes
Try AssImp. It's an open C++ model loader that supports a bunch of different formats.

---
Tags: opengl, c++, opengl-es, models, importing
---


# Question
Title: OpenGL vs OGRE : Which is the best for beginner?
I am interested in getting into game development and posses good C/C++ programming skills. I have tried OGRE before, and I am curious whether I should learn either OGRE or OpenGL as a starting point.

From my understanding, OGRE is a wrapper for OpenGL and DirectX. So, supposed that I learn OGRE, do I still need to learn OpenGL as well to develop a game?

Also, can someone points me good tutorial for OpenGL? I found that OGRE is well documented (it's even come with the distribution!) but for OpenGL, most of the tutorials I came over are outdated.

# Answer
> 13 votes
Ogre is indeed a wrapper for OpenGL, however the idea of such a wrapper is that you don't have to concern yourself with the intricacies of OpenGL. It will of course help to know a bit about OpenGL, but Ogre will hide a lot of the ugly details for you.

I would say that Ogre is arguably easier to learn as opposed to OpenGL, or at least it will get you interesting results faster. Of course it totally depends on what you would like to do to asses if it's worth learning OpenGL.

About OpenGL tutorials, yes most of them are pretty outdated, however the spec hasn't been moving forward really fast so a lot of those old tutorials still apply to most of OpenGL.

A few of my favourites:

# Answer
> 17 votes
OpenGL! Yes I'm openly disagreeing with everyone on this board so far.

OGRE is a mess. The learning curve is steep. Yeah they've got some nice tutorials, but stepping outside the bounds of the tutorials and doing your own thing is VERY difficult. I'd expect to spend a three weeks before you can get OGRE set up and working, work through the tutorials, and figure out what to do next. There's nothing about OGRE that is THAT much better or simpler than OpenGL. If you are a good C programmer as you've claimed, and you understand your pointers/arrays/functions, OpenGL will be just as easy, if not easier.

That's why I strongly recommend starting with OpenGL. OpenGL will force you to learn all of the fundamentals of graphics. It's a lot more interesting as you'll actually come to realize what they heck is going on in the background. And YES start with NeHe's tutorials. Yeah they are 1.x which is very outdated (this is for you, Ranieri), but jumping into OpenGL 4.x is too steep a learning curve.

Start out with the immediate mode in 1.x (glBegin, glEnd), then learn about Vertex Arrays. If you want, play with display lists just to learn. Then move towards vertex buffer objects. Then learn about shaders. Each of these transitions are very easy, and there are plenty of great tutorials online. VBO's are in the core of 4.1, so by the time you make it there, you are no longer learning outdated material, and it's a lot easier to get there by starting with the 1.x stuff.

Also, if you ever want a game development career, nobody is going to hire you because you can make a cube spin in some off the shelf library. They are going to hire you because you understand what is going on at the lowest level possible and you can make design decisions based on that valuable knowledge.

References: I was where you were. I spent a month on OGRE, a week trying out Irrlicht, a week trying out Horde3d, two days playing with DirectX, and a month playing with OpenGL. After a month with OGRE I could barely go beyond the scope of the tutorials. After a month with OpenGL I had a character running around a minecraftian world, rendering 260,000 textured cubes per frame with 700+ framerate.

# Answer
> 5 votes
Short answer? OGRE.

Longish answer? OGRE is a wrapper over OpenGL, so therefore you have to do a lot less work. You do not have to worry so much about sending data to the GPU or binding shaders, or sorting out vertices at a low level. It is much faster to use OGRE than to use OpenGL for production, and chances are your code will be (very marginally) faster too.

If you're interested in engine development, use GL. Else, use OGRE. And I'd probably start with OGRE anyway.

# Answer
> 3 votes
Knowing computer graphics hardware is not needed for game development. It is needed to become graphics programmer or part of render dev team in a game company (Personal note: which is the best fun on whole game development :)).

If you dont wish to become render engineer, you propably don't need to learn whole openGL or DX to develop games.

# Answer
> 2 votes
I would argue neither is best for a beginner, but then "best" is a relative term that depends what exactly you are looking to gain. For example, if what you're wanting is to learn 3D graphics programming in order to gain skills that you could use to get a job as a 3D graphics programmer for a games company then those choices make sense. With this goal you might also look at DirectX.

If however you have any other goal in mind then I would recommend looking at other options. For starters, while from your question one would assume you want to be involved in game development as a programmer, you didn't actually specify that. Both writing a graphics engine in OpenGL and building on top of Ogre are definitely for hard-core programmers.

---
Tags: opengl, ogre
---


# Question
Title: Trying to understand relatively simple normal map antialiasing paper
See this paper: ftp://download.nvidia.com/developer/Papers/Mipmapping\_Normal\_Maps.pdf

They describe the very simple implementation of an algorithm for antialiasing normal maps.

I don't understand exactly how to look up an appropriate value in the lookup table they describe.

A value is accessed with (N\_a . N\_a, N\_a . H).

My specular light for example, is computed with:

```
        result.Specular += baseIntensity * SpecularColor *
            pow(max(0, dot(H,N)), SpecularExponent);

```

The `H` is the same as the `H` in the paper. `SpecularExponent` is the `s` in the paper. The `N` is the vector that results from looking up a normal in the normal map (which is already normalized) and then transforming that normal into world space.

What is `N_a` then?

It seems that the lookup table is constructed by taking all of the normals (N\_a) in a normal map, and then taking all (or many) of the values that H can take, and forming a table from these according to the formula they provide.

However, this doesn't make sense to me, how is the normal that is transformed into world space taken into account in the lookup table then?

That is, the normal in the normal map is rotated to be on the mesh that the normal map is being applied to. So this new rotated normal is what we use to calculate the specular exponent -- how does this fit into the use of the lookup texture?

My best guess right now is that N\_a is actually the normal from the normal map that is already transformed into world space. Otherwise, I guess it is just the normal from the normal map, and they ignore the transformation into world space.

# Answer
> 2 votes
N\_a is the result of the normal map fetch, which is usually not unit length because it is a linear blend of almost-unit vectors.

The normal map typically encodes normals in tangent space, which is to say that a normal in the map with the value \[0,0,1\] points directly away from the surface along the surface normal.

You are right that N\_a is "the normal ... before transformation into world space" in the typical case. Take care that the "H" in "dot( N\_a, H )" is in the same space as N\_a.

# Answer
> 3 votes
`2.` They may not always be normalized after transformation into projection or world space, even if you provide the correct inverse transpose of the vertex transformation.

---
Tags: hlsl, normal-mapping, antialiasing
---


title: Am I on the right track with Pong?

text:
# Question
Title: Am I on the right track with Pong?
I'm a web developer who is trying to know more about game development.

I've started trying to make Pong using canvas, just to see how far I can go (and what I can learn along the way).

I have heard a lot about the *game loop* but being a novice was not sure how it applies to Pong. I figured it would be something like a `setInterval()` that changes the game's state as it runs (ball movement, enemy position, etc).

I have also created two objects, `Paddle` and `Ball`, but looked at implementing the bouncing inside one of `Ball`'s methods. I'm not sure if that is right.

What I want to know is *am I on the right track*? What suggestions would you have to my code in terms of layout/structure (and any recommended reading)?

Most of the articles I found regarding JavaScript game development were horribly outdated or didn't deal with canvas; only animating DOM elements.

# Answer
> 7 votes
This is a very common problem. To solve it right you need to make sure the game time and the game framerate are not dependent (you don't want all you game elements to move slowly if the framerate is low and faster if it's high). From my point of view setInterval will not be efficient. Here is what I suggest:

You need to have three methods in your game: main (that we will try to run 60 times per seconds), update (that will update elements positions) and draw (that will display all the elements) and a variable to store the current time. Initialize your currentTime variable to now then start your main method.

Here is what your main method should do:

* compute the time elapsed since the last execution of the main method (timeElapsed = now - currentTime)
* reset the current time variable (currentTime = now)
* run the update method with timeElapsed has argument
* run the draw method
* compute the time elapsed since we started the main method (timeElapsed = now - currentTime)
* compute the time wee need to wait before running again the main method for an expected framerate of 60 frame per seconds (timeout = 1000 / 60 - timeElapsed)
* prevent this time from being less than zero (timeout = timeout \< 0 ? 0 : timeout)
* schedule the next execution of the main method using setTimeout: setTimeout(main, tiemout)

Then in your update method multiply every translations operations by the elapsedTime variable passed has argument (x = x + speed * elapsedTime). This way, if the ball has a speed of 1.6 it will always move 96 pixel per seconds even if the framerate too is slow or too high.

This way you make sure the game run at (almost) exactly 60 fps all the time and that you elements moves at the right speed even if the framerate changes for some reason.

Implementing the bounce logic within your Ball class is up to you. Try to write your game step by step and do not hesitate to change and move your code so it always looks simple. There is no "right way" to do it. I suggest you give a look to this project (a nice javascript pong game but without canevas). It does implement the loop method described above. You can also test it here.

I hope this help ! Good luck !

# Answer
> 4 votes
Yes you're on the right track. In some languages the main loop is written with an explicit "while" loop, but in many languages you want to hook into a built in main loop using an event listener or callback. JavaScript is the latter.

---
Tags: javascript
---


title: Can You Make an iPhone game for Free?

text:
# Question
Title: Can You Make an iPhone game for Free?
A friend and I want to try making an iPhone game, but we don't really have a budget to speak of. From what I've found, I need the iOS SDK, and that costs money. Is there really no way to make an iPhone game on a $0 budget? If not, can I do so for the Android?

# Answer
The Airplay SDK: http://www.airplaysdk.com/ as well as some other other mobile SDKs, will let you make iOS games for free (in the sense that you don't have to buy a Mac), but I believe it will still cost $100 to get your game on the app store, no matter what tool you use.

The Android is free to develop for and deploy to (Edit: per the comment by Ricket, it's actually $25 to publish on the app store). You can also make an HTML5 web game, and people with iPhones can play it in their browser, at no cost to you (or them).
> 11 votes

# Answer
None of the other answers addressed a basic misconception in your question: the iOS SDK does not cost any money. You can download Apple's developer tools for free. However you will only be able to test in the simulator for free; in order to deploy onto device you need to purchase the $99/year developer registration.

The fee is for the ability to publish, not for the SDK. Subtle but important distinction.

So no, there is no way to make an iPhone game without paying a fee. Android does not have any fee to deploy to device, but the individual marketplaces have their own policies.
> 12 votes

# Answer
If you want to publish or test it then no. The minimum you can spend to publish a game is the yearly $99 fee that you are talking about for the SDK. Apple simply won't let you post a game to the app store if you aren't paying to be a developer.

If you want to make one and maybe publish it later, find a game engine like Unity3d that will let you make it for other platforms and easily port it to iphone when you're ready. That's the route my team took a few years ago when we were just starting. We made our game for Unity's browser plugin then ported it over to IOS when we bought the license.

EDIT: FYI, unity and a few other engines are completely free just for this purpose. Once you want to publish to iPhone though you will need to also buy the unity IOS basic license at minimum which is $400, but if you have a game worth anything you may find somebody willing to pay for your licenses for a percent of the game.
> 3 votes

---
Tags: iphone, costs
---


title: Inverting matrix in HLSL

text:
# Question
Title: Inverting matrix in HLSL
I've got an object in HLSL and I'm using hardware instancing to render multiple copies. But I've come a bit of a cropper when it comes to the vertex normals. Currently I am not using normal mapping (although planning to implement it soon), I'm just putting the normals inside the vertex structure. I can put the world matrix and get it out in HLSL just fine, but I need the inverse transpose if I want the world position of the vertex normal from object space. How can I invert a matrix in HLSL? Or am I going to have to send the matrix and it's inverse in the instance buffer?

Or is this somehing that normal mapping doesn't require?

# Answer
> 8 votes
> Or is this somehing that normal mapping doesn't require?

That's right, normal mapping doesn't require this.

In most cases the best way to do normal mapping is to store the normal map normals in tangent space. That is, a normal in the normal map pointing in the same direction as the surface normal is \<0,0,1\>. (This is why many normal maps are mostly blue, since they are stored in tangent space.)

Instead of transforming every normal in the normal map into world space (as you're about to do), you can just transform the lights and camera into tangent space on the CPU before the draw call. Then no transformation of the normal map normals is needed.

This means that you will do perhaps 2-10 matrix multiplications on the CPU, saving thousands or millions of transformations on the GPU.

See this article for a more in depth explanation of normal mapping and tangent space: http://www.gamasutra.com/view/feature/1515/messing\_with\_tangent\_space.php

# Answer
> 7 votes
HLSL does not provide a function for invert but it does provide for transpose. So if your matrix is orthogonal you can just use transpose.
Also if you have scaling and is uniform you won't need the inverse transpose matrix. You can just use the world matrix to rotate your normal and then normalize it.
I apologize If I haven't understand your problem correctly.

# Answer
> 5 votes
Don't - you'll have to do it for each vertex for a regular vertex shader and this is a massive waste of GPU time. Anything complex like this that can be pre-calculated should be pre-calculated.

---
Tags: directx, hlsl, matrix
---


title: Game World structure in classes

text:
# Question
Title: Game World structure in classes
I am developing 2D game in java, and I want some basic in-game scripting (spawn enemy, spawn item, change enemies properties).

What I don't know is, how to divide the game world, to easily work with it.

I need enemies (have health, basic AI) of different types, item classes (can be picked by player), tile map with different blocks. Whats the best solution to maintain the whole world and to what classes should I divide it, to easily extend?

# Answer
I think it is also highly dependent on how your overall application is structured. You should ideally separate functionality as much as possible.

Naturally we all want to see a code example, so I'll give it my best shot. Though to be honest, this all means nothing without being related to your own specific examples. Perhaps just do some basic prototypes, and when it gets clunky (and it probably will), re-factor. Iterative design accomplishes so much more than if you try to plan it all at once; in which case you meet constant mental blocks; and may even lose motivation.

```
class Renderer;

class Mesh {
    Vertex Data etc;
}

class WorldObject {
    Position, Rotation
}

class Movable {
    Velocity, Acceleration;
}

class Terrain {
    WorldObject;
    Mesh;

    draw() { Renderer.draw(Mesh, WorldObject); }
}

class Entity {
    WorldObject;
    Mesh;
    Movable;

    draw() { Renderer.draw(Mesh, WorldObject); }
    update() {
        // update position based on velocity/accelerate
    }
}

class World {
    Terrain;
    Entities;

    draw() {
            Terrain.draw();
            foreach Entities
            {
                entity.draw();
            }
    }
    update() {
            foreach Entities
            {
                entity.update();
            }
    }
}

class Animation {
    Animation data etc;
}

class AnimatedEntity : Entity {
    Animations;
}

class Health;
class Gear;

class Character {
    AnimatedEntity;
    Health;
    Gear;
}

class Situation {
    Entities enemies;
    Entities obstacles;
    Position;
}

class AI {
    Brain;

    React(Character, Situation) { ... }
}

class NPC {
    Character;
    AI;
}

```

This could go on forever; the implementation of functions you described (spawn enemy etc), are just methods you can write that create these objects with particular properties, or modify them.

Obvious points, avoid code duplication, but don't go inheritance crazy, otherwise you will run into pitfalls really quickly because of cross-tree dependencies. I have greatly avoided inheritance here, simply to make a point, but if you find it appropriate it, I'm sure you can implement it differently.
> 3 votes

# Answer
I guess I'll post my answer here to...

I usually have a layout similar to this.

`GameObject` has functions such as `Draw()` and `Move()`. Then `Enemy` sets up some more functions and variables for implementing Artificial Intelligence in `Goblin` and `Unicorn`. `Player` contains all the stuff for moving the player in `Move()`.

Thats just a general idea of what I would do. Its different for every game, depending on what type of game it is and how you play it.
> 2 votes

# Answer
dont know if i'll be bashed for posting my answer twice .... but well... didnt see this one and this is kindof more appropriate place

game world basics to me are about finding common grounds.

the world going forward in time. so are all active elements (player, dropped items, enemies, npc's) but all passive elements are not (block of stone, tree, house) therefor i'd use 2 interfaces ActiveElement and PassiveElement. the active element could have a stepintime() function which is called by the game world each time itself steps in time. both elements could have a render() function which draws the element whenever the gameworld is drawn on a canvas.

then all enemies should call their ai to determine their next step in time as well as checking collision with any other objects and whatever that means (trees bullets players etc) same goes basically for every other element.

this is to me the most basic architecture in gameworlds.

then there's the issue of performance where it might be better to put certain things in their own threads and let them run (enemy ai that is checking the position and status of his avatar each cycle and makes input which is read with each step in time) but there i dont have enough experience in to elaborate. then you should go to a gamedev site (eg as karim79 said).

implemented elements can have their own attributes then and is easy to expand(health, stats) and write an interpreter that reads simpel scripts that communicates with the gameworld adding enemies etc.

ciao
> 0 votes

---
Tags: architecture, java
---


# Question
Title: Need an ideal opensource 3D engine for building Golf simulation game
I'm looking for a open-source 3D graphics and physics engine specialized in golf simulation.

The preferred engine would be have short learning curve, supports Windows platform and Java or C++ and Lua/Python support for scripting, also prefer something like outdoor golf plane scene with weather system support, I'm new to this area and would love to hear all of your advice.

I'm just come from stackoverflow site, @mikera there recommends jMonkeyEngine, it sounds a fit, but I'm not sure if there's other ideal candidate engine?

# Answer
> 4 votes
Try Ogre3D as a graphics engine and bullet as a physics engine.

---
Tags: opengl
---


# Question
Title: Operations on multiple overlapping layers not working
Hi I am developing a game in android just like Farmville by Zinga. In that game we have to place elements in the diamond shaped field so the don't overlap each other. Now I did coding for placing the field inside the farm field but I cannot stop the problem of overlapping of the farm field. I Am attaching the code that I have down for all this someone please help me....

```
try{
    if(bm1.getPixel((int)initX,(int)initY)!=0){
        if(bm1.getPixel((int)initX,(int)initY+20)!=0){
            if(bm1.getPixel((int)initX-20,(int)initY)!=0){
                if(bm1.getPixel((int)initX+20,(int)initY)!=0){
                    if(bm1.getPixel((int)initX,(int)initY-20)!=0){
                        c.drawBitmap(bm,initX-30,initY-20, paint);
                    }
                }
            }
        }
    }
}catch(Exception e) {
    Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT);
}

```

# Answer
I wonder why you're choosing a pixel based collision detection here? A game like Farmville works with a tile-grid. I assume you have such a data-structure in your game that holds all the tiles? Why not simply query this data-structure and look up if a tile is already occupied? If yes, snap the new tile to an adjacent field, or simply prevent the user from dropping a new element there.

**Update**: Have a look at the following screenshot:

I drew some lines (white) over it to show you the tile grid. The smallest grid size is probably the size of the small pink rhombus. Of course you can also use bigger tiles, like the 2x2 tile (also colored pink). The Farm-House is a 4x3 tile.

When you place a new element on that grid, you can check if any other tile is already at that position. For a 2x2 tile, you'll only have to check 4 grid cells...

It is of course up to you how coarse your grid should be.
> 1 votes

---
Tags: collision-detection
---


# Question
Title: How do I open the camera in a CCScene node in a Cocos2D application?
I am new to Cocos2D and I can't find the way to open the camera from the library. I want to open the camera in the my game, can any one help me with with this?

Thank you in advance.

# Answer
I guess that CCRenderTexture is what you are looking for.

Take a look at this example
> 1 votes

---
Tags: iphone, camera, cocos2d
---


title: Making a game as a tutorial?

text:
# Question
Title: Making a game as a tutorial?
I am in charge of a game development club at my school and I'd like to work on a project this summer that I could use as a tutorial next semester. I have never done anything quite like this so I was wondering if anyone had any guide lines or ideas.

What I want to do basically is make a very simple game. Something like a top-down shooter where enemies come rush in for you to kill them and pick up some loot. However, I want everything to be very easily modified. The people in the club have little game development experience, so if I could set up my game in such a way that people could modify and add functionality with ease, it would be great for them.

Stuff like having an enemy class where the behavior is easy to play with, or making guns shoot differently/adding new guns, and new loot. Even adding new elements to the game. What would be the best way to build the game to allow this kind of malleability?

# Answer
> 16 votes
A traditional way to accomplish this goal in game development is to use a data-driven architecture for the game systems.

In essence, this means that code does not implement a particular type of weapon (a gun) with explicitly defined values for its range/damage/penetration rather it populates the generic concepts of a ranged weapon (range/damage/penetration...) from an external (to the code) data source. This external source can vary from parse-able (perhaps XML) files read in from disk, to binary files or database elements generated via tools internal or external to the game engine itself.

Defining something like an enemy, the AI system might be designed to support some number of generic behaviors (aggressive, defensive, support, coward) which are then tweaked by data driven elements.

My New Enemy, starts with the aggressive base AI behavior with data-driven values for: -ignore players \> my level + X -pursue players up to X units beyond spawn point -flee when health \< X -ranged ability priorities -melee ability priorities (for when players get too close)

A more complicated data driven scheme might allow the definition of specific data points (events) where an AI state transitions (finite state machine) to another state (or even a chance to transition to one of N other states) allowing your users to define a complicated hierarchy of behaviors.

All of this is of course more work than just coding explicitly a behavior, but its a fun challenge to enable users to produce content without modification of the source.

There are bonus points to be achieved:

* if you can dynamically update data and have the changes reflected within the game engine without restarting the application
* if you create user friendly UIs over the data allowing users to use an interface to interact with the data rather than directly editing text (xml, or whatever) files

For a tutorial game targeted as a more technical crowd, most of the work is instead in designed classes/objects that expose clean interfaces for the users to extend which in turn may also be data-driven.

# Answer
> 1 votes
If you're looking for a few ideas on how get your project started and build it up step by step so it can be converted to a tutorial, have a look at XNA Game Programming Adventures. The author has several tutorials set up, with explanation and source code that increments step-by-step.

# Answer
> 0 votes
I would suggest looking at the Java Game Development tutorial on www.thenewboston.com

It may not be exactly what you're looking for in terms of dudes with weapons and all that jazz, but it gives a nice step by step breakdown of a number of key factors in game developement. The presenter "Bucky" also has a chilled out, just-for-fun style of teaching. Enjoy.

---
Tags: xna, game-design
---


# Question
Title: How to make a hand-drawn squared texture periodic with as little modification as possible?
The obvious part is drawing as periodic as possible, but hand-drawing is impossibly so perfect, so what kind of modifications are possible that do not make the textures loose their hand-drawn character?

# Answer
> 2 votes
There is an excellent, GIMP Plugin filter called Resynthesizer (webpage here) which, among other tricks, can make a tileable texture. Have a look at the section in that web page called "Creating more of a texture".

Once you have it installed, put your source texture in the middle of a larger image, select your source pixels (or just use your original image and select a subsection of it) and then 'select-\>invert' to get the bits you need to fill. As long as you give it enough pixel area to work with, I've found it tends to do a really nice job.

# Answer
> 7 votes
I would suggest doing this manually in software like Photoshop.

In Photoshop there's a filter called offset which scrolls the image by the given amount of pixels. If you offset by half the images width and half the images height you'll see the seams in the middle of the image. You can then alter the image until the seams are no longer visible. When you've done that, use offset again to make sure you haven't created any new seams.

This tutorial may be of help.

# Answer
> 3 votes
In GIMP you can use the "make seamless" filter (this can also be scripted). If the results aren't good enough, the best way is a manual approach as described in the answer by CiscoIPPhone.

This tutorial lists several possibilities using GIMP, including the "make seamless" filter.

---
Tags: textures, hand-drawn
---


title: Any good books on graphics programming?

text:
# Question
Title: Any good books on graphics programming?
I've been looking for a book that takes a bottom-up approach for graphics programming. So something that starts with 2d filtering, maybe moving into normal mapping, then ambient occlusion, etc.

I ask because I've been lazy for the last few years in game development and always used an engine that handles this. I want to start writing some shaders for my games instead of relying on the cryptic ones that I've borrowed in the past. I think a very strong knowledge in this will help and I'm a bottom-up kind of learner so please help me out!

I know the GPU Gems series is great, but they seem to be more like a cookbook than a bottom-up approach that I want. You tend to get more scattered theory from cookbooks instead of building on theory from previous chapters.

EDIT: Preferably something you've read! I can search amazon for this, but it's hard to get a unbiased review that way.

# Answer
> 10 votes
Most "shader effects" like filtering and normal mapping have very little in common that could be considered building blocks between effects. 2D filtering and normal mapping aren't any more difficult or advanced than each other, for example, and the same is true of many effects with only a few notable exceptions (the various flavors of shadow mapping come to mind). They're just different. That's why you'll see so many cookbook-style books when it comes to discussing actual graphical *effects* programming (as opposed to graphics programming at a fundamental level).

Most in-world effects (i.e., not post-processing ones) are rooted at some level in the physical properties of light and the simulation or approximation thereof. To that end, reading books that focus on ray-tracing as a rendering method may help you better understand the core theories involved (Physically Based Rendering is also an excellent read).

Once you understand that, the "scattered theory" present in books like GPU Gems will relate primarily to the specific ways in which the GPU can be manipulated to approximate the real-world physical scenarios desired, and will seem less disjointed.

Similarly, post-processing shaders tend to draw from signal and image processing theory. I think I recall having this book as a textbook in a class on the subject, but don't recall too much about it.

In general, though, you aren't going to find too much that caters to that kind of approach because the theory that binds together all the various shader effects that are in vogue right now is structured like a very, very shallow tree rather than a very deep one -- there are very few dependencies that cater to "bottom up" approaches once you get beyond the fundamentals of graphics programming theory itself (how to structure the scene, the transformation pipeline and associated linear algebra, rasterization, et cetera).

---
Tags: shaders, graphics-programming, graphic-effects
---


title: How to store 'dots and boxes' data?

text:
# Question
Title: How to store 'dots and boxes' data?
I'm trying to explore a little as to how I could make a simple 'dots and boxes' game.

The problem I'm facing is in what way to store which lines are allocated by who. The problem lies in the fact that all inner lines are shared by neighbour boxes. So I can't just have four variables on each box because the right line of upper left-hand box is actually the same as the left line of box next to it. So I'd need them to be stored in one variable.

What technique of saving this data would be practical in this case?

# Answer
It's not actually a problem. What you need to do is make sure that lines are shared references, not simply variables.

So if you have two boxes, A and B, sharing a line:

```
.  .   .
 A | B
.  .   .

```

Then a.RightLine and b.LeftLine both point to the same reference. Or, if it's a boolean, when the user clicks on the line, make sure you update both A and B to keep track of that fact.

Another solution might be to keep a hash-map of lines, where the key is the indicies of both boxes plus the line side.

So the above example would be something like:

```
lines["A, B"] = solid

```

Because you can uniquely identify a line with two boxes, since every pair of boxes only have one shared side.
> 2 votes

# Answer
The way I've traditionally handled it is as two arrays of lines: one n-by-(n+1) array of vertical lines (one for each row and one for each column-plus-one - there's the one to the left of each column and then the last set of vertical lines on the right), and likewise, one (n+1)-by-n array of horizontal lines, one for each row-plus-one and one for each column. This requires a very little special-casing (the two boxes you'll have to check for matches when a line's drawn are different for horizontal vs. vertical), but it also allows for easy indexing of the lines corresponding to a given box (the edges of Box\[a,b\] are HLine\[a,b\], HLine\[a+1,b\], VLine\[a,b\], and VLine\[a,b+1\]).

And if you ever decide to make the game more sophisticated (especially on an AI front), then you'll probably want a more abstract representation for strategic purposes: you may want to look into Nimstring and Berlekamp's dots-and-boxes book - a lot of positions that look completely different on the board are actually identical from a mathematical perspective (for instance, 'chains' of boxes with two walls closed off and two open to the next-and-previous box).
> 2 votes

---
Tags: game-mechanics, memory-efficiency, storage
---


# Question
Title: Are there any web frameworks used primarily to produce games?
Basically, the title says it all. I've seen and worked with Django, Rails and a bit with Cake PHP. I'd like to know if there is a framework that is excellent for supporting casual, 2d, browser based game development. The closest that I've seen is flash, but I'd like to find something open source. Something that could handle both the graphics and communication to a database would be ideal. Any suggestions?

# Answer
> 3 votes
I maintain a list of resources related to javascript game development that i have found useful, including a list of game engines and web services you can integrate.

You need to keep track of two different concepts: Client side presentation and server side processing. If you are developing a casual flash-style game the complete game will probably be the client side presentation, mixed with some web services for highscore and the likes. However, if you want to do social-, mulitplayer- or mmo style games a lot, if not most of the game will be on the server to prevent cheating, and the client will just act like a dumb terminal. How that is handled is probably a topic for another question.

Of interest to anyone who wants to communicate in realtime between browser and server should be socket.io that is an abstraction on top of websockets with fallback using flash in older browsers.

# Answer
> 6 votes
There are several game engines/frameworks emerging with HTML5. Here are some links that might be of interest:

Apart from the Rocket Engine, these engines just cover the client side of a game. So there's no direct communication to a database (unless you're using something like Google Gears).

Depending on your game, you still have to implement some backend stuff in Ruby, Java, PHP, ASP or similar. IMHO any regular web-application framework will be sufficient for that. Node.js probably deserves a special mention, because you can implement the backend in the same language as your game (JavaScript).

# Answer
> 1 votes
The thing is, in web development, a large part of the presentation would typically be done on the server side (using a framework that embeds some sort of templating system to output HTML to the client). If you want to do interactive game, a lot of the work has to happen on the client side (in the browser), so the problem is not so much how you generate HTML, but rather how you make things move on the user's screen.

For this client-side part, as mentioned, your choice are either Flash or JS (potentially using Canvas for modern browser).

For the client-server-db communication part, any of the technology you mentioned would be fine. The browser and server can communicate using classic ajax calls if you need.

I don't know of a framework that would handle both problems, but that's probably because they are really distinct, and happening on different side of the client-server mix.

---
Tags: browser-based-games, casual-games
---