# Question
Title: does opengl automatically handle offscreen rendering?
I'm wondering if opengl can automatically manage offscreen rendering. I mean if it can detect and ignore sprites and textures if they are rendered out of screen.

if it makes any difference i'm targeting opengl-es 2.

# Answer
> 2 votes
To bind a texture in OpenGL-ES 2.0, the texture must be in memory. Whether or not the texture gets used depends on whether an object remaining in the viewable scene uses that texture. So, yes, it can ignore the texture for rasterization, however, to your point of a 2048x2048 texture on a 480x320 screen, as the Apple "OpenGL ES Programming Guide for iOS" states on page 71:

> ## Reduce Texture Memory Usage
>
> Reducing the amount of memory your iOS application uses is always an important part of tuning your application. However, an OpenGL ES application is also constrained in the total amount of memory it can use to load textures.

And on page 72:

> ## Use Properly Sized Textures
>
> The images that an iOS-based device displays are very small. Your application does not need to provide large textures to present acceptable images to the screen. Halving both dimensions of a texture reduces the amount of memory needed for that texture to one-quarter that of the original texture.
>
> Before shrinking your textures, attempt to compress the texture or use a lower-precision color format first. A texture compressed with the PVRTC format usually provides higher image quality than shrinking the texture—and it uses less memory too!

You can apply the same logic to most OpenGL-ES 2.0 devices, since they each have limited memory.

# Answer
> 5 votes
If an object, when translated to the 2D display, is not within the buffer's dimensions then OpnGL will do nothing with the data.. However it still has to do a bit of processing to get to that point so it is still considered better practice to only send things to OpenGL that actually have a chance of being seen on the screen in one manner or another.

Scene Graphs are the constructs that are commonly used to determine which objects to send down the graphics pipeline for processing or not.

Hope this helps.

# Answer
> 1 votes
> I mean if it can detect and ignore sprites and textures if they are rendered out of screen.

In general, if you're thinking solely in terms of 2D graphics, "sprites and textures", rendering performance is not going to be a concern. Not on any hardware you can actually have bought in the last 8 years.

You might be drawing, what, a few hundred quads every frame? Maybe a thousand, tops? You could do that on a Voodoo 1 at 60fps no problem, and that was with *software* T&L.

You don't need to concern yourself too much with parts of quads that happen to be off-screen. GPUs aren't stupid; they will not do work that will not have a visible effect. Remember: hardware makers make money based on how fast their cards go. And spending time on the part of a triangle that's off-screen is time that could have gone to stuff that's on-screen.

Now, that being said, it's not a bad idea to do some simple visibility checks to see if a quad is actually on screen or not. But the key word is "simple". At no time should you modify a quad so that you're only rendering the visible portion; just let the GPU do its job.

---
Tags: opengl-es
---


# Question
Title: All Pairs Shortest Paths in Weighted Undirected Graph
I'm currently working on path-finding for my game and need help with finding an efficient algorithm to calculating the all-pairs shortest paths in a weighted undirected graph (each vertex in the graph represents a way-point on my map, and each edge represents the distance between pairs of way-points).

I have considered using Floyd's Algorithm due to its simplicity and relative memory efficiency, but Floyd was designed for a *directed* graph, whereas my graph is *undirected*. This means that Floyd's algorithm is rather more expensive than required given that I know that the shortest path from vertex A to vertex B is always identical to the shortest path from B to A.

Can Floyd's algorithm be optimized to deal with this duplication? Or is there an alternative algorithm fast/space efficient algorithm that I could use to solve the same problem?

# Answer
Sure. In the implementation in Wikipedia, change the inner loop to `for j := i+1 to n`, and replace all `path[X][Y]` with `X < Y ? path[X][Y] : path[Y][X]`.
> 3 votes

---
Tags: algorithm, path-finding
---


title: Enemy Movement AI

text:
# Question
Title: Enemy Movement AI
I have a non-tile-based top down shooter game, and I have enemies set up. However I need the enemies to move to the player. Pathfinding algorithms will mean the enemies will just hug the wall. The map has many walls and objects for cover.

How is it done in other games and what should I do?

# Answer
First of all if your map is not tile based, you need to create a navigation mesh out of it.

Second thing you will need is a good pathfinding algorithm. A\* is a good one to start with.

Third you will need to add some intelligence to your pathfinding so it will go throught the doors that can be opened and avoid those who can't, I am sure you will find a way.

Fourth, if you want to make your AI look smarter you can smooth their path with some steering algorithm (or you can look at what valve did for left4dead)

And then I guess this would be a good start :)
> 6 votes

---
Tags: path-finding
---


# Question
Title: Create a body of an irregular 2D sprite in Farseer
I'm trying to create a body of a irregular 2D sprite Farseer 3.3.1.
The regular shapes that `BodyFactory` provides are not that I want. Is there a way that one can create irregular objects? Could it be done using the `BodyFactory.CreateCompoundPolygon` method?

# Answer
> 2 votes
Farseer Physics Engine's support of polygons is otherwise well-documented. Although the documentation may need to be updated to the latest version.

You can create polygons using a list of Vertices, which (simply put) are just the coordinates of all the corners. Vertices can either be defined in code, or be generated on the basis of an image file using some of the tools provided.

Straight from the documentation:

```
  //load texture that will represent the physics body
  Texture2D polygonTexture = GameInstance.Content.Load<Texture2D>("Texture");

  //Create an array to hold the data from the texture
  uint[] data = new uint[polygonTexture.Width * polygonTexture.Height];

  //Transfer the texture data to the array
  polygonTexture.GetData(data);

  //Find the vertices that makes up the outline of the shape in the texture
  Vertices verts = PolygonTools.CreatePolygon(data, polygonTexture.Width, polygonTexture.Height, true);

  //For now we need to scale the vertices (result is in pixels, we use meters)
  Vector2 scale = new Vector2(0.07f, 0.07f);
  verts.Scale(ref scale);

  //Since it is a concave polygon, we need to partition it into several smaller convex polygons
  _list = BayazitDecomposer.ConvexPartition(verts);

  //Create a single body with multiple fixtures
  List<Fixture> compund = FixtureFactory.CreateCompoundPolygon(World, _list, 1);
  compund[0].Body.BodyType = BodyType.Dynamic;

```

To get textures (sprites) from polygons generated on-the-fly instead of from an image file, you need a little extra code. In the samples project bundled with the latest version of FPE, there is a class called AssetCreator that can generate polygons on the basis of vertices and a base (fill) texture.

Once you have added the AssetCreator-class and its dependencies to your code, you can use it to generate polygon textures e.g. like this:

```
        AssetCreator assetCreator = new AssetCreator(graphics.GraphicsDevice);
        assetCreator.LoadContent(this.Content);

        Vertices vertices = new Vertices();
        vertices.Add(new Vector2(ConvertUnits.ToSimUnits(0), ConvertUnits.ToSimUnits(0)));
        vertices.Add(new Vector2(ConvertUnits.ToSimUnits(20), ConvertUnits.ToSimUnits(0)));
        vertices.Add(new Vector2(ConvertUnits.ToSimUnits(30), ConvertUnits.ToSimUnits(30)));
        vertices.Add(new Vector2(ConvertUnits.ToSimUnits(10), ConvertUnits.ToSimUnits(60)));
        vertices.Add(new Vector2(ConvertUnits.ToSimUnits(-10), ConvertUnits.ToSimUnits(30)));

        //polygon body
        PolygonShape shape = new PolygonShape(vertices, 1);
        sprite = new Sprite(assetCreator.TextureFromShape(shape, MaterialType.Blank, Color.DimGray, 1f));
        body = BodyFactory.CreatePolygon(world, vertices, 1f);
        Fixture fixture = FixtureFactory.AttachPolygon(vertices, 1f, body);
        fixture.Body.BodyType = BodyType.Dynamic;

```

I hope this is helpful. If it is, please mark my answer as 'Answer'.

# Answer
> 1 votes
I haven't used Farseer, but I have used Box2D. In Box2D, the polygon must be convex. To get away with non-convex polygons, you had to triangulate them.

There are a number of triangulation algorithms out there. *I think* we used the Ear Clipping algorithm.

---
Tags: xna, c#, sprites, xna-4.0, farseer-physics-engine
---


# Question
Title: Which parts of my game should be Activity objects?
Currently my game has an Activity for the *splash screen* then it starts the *main class activity* then it starts a *menu activity* then from the menu there is an activity for each option (only two at the moment), *Start* and *About*.

```
Splash --> Main --> Menu --> (Start, About)

```

The start then sets a Content View for my game to draw to the screen.

What additional parts to a game should have or require an activity and what parts that I may or may not have don't need to be an Activity.

---

**Activity:**

> An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View)

---

Since we know what an Activity is, now I am just looking for places that it would be used in a game?

**UPDATE**

We have a great explanation of the game architecture in Android. This diagram is awesome!

# Answer
Use a single activity. Have a look at the basic game architecture here: http://www.thegamecoder.com/blog/?p=46

Implement your menus inside the MainView class in the link.
> 4 votes

# Answer
Have a look at Replica Island. It's written by one of the Google engineers. They use different activities for everything. But I think using one activity is way easier! Other games and some of the available game engines do it that way. The downside is that you have to implement behaviour like button presses etc. yourself.
> 2 votes

---
Tags: architecture, android
---


# Question
Title: Calculating the angular direction from velocity
I'm trying to calculate the angular direction of a projectile, knowing it's X and Y velocity I can find the magnitude of its movement, but I'm having a hard time wrapping my mind around getting the angular direction (in radians) that it is moving...

I assume there is a `tan` or a `sin` involved, but I'm a bit clueless otherwise...

# Answer
read the following page you have to use atan2 : http://www.w3schools.com/jsref/jsref\_atan.asp

so `angle = atan2 (vy,vx);` and `speed = sqrt(vy*vy + vx * vx)`
> 11 votes

# Answer
angle = tan\_inverse(VelocityY/VelocityX)
> 0 votes

---
Tags: 2d, physics, javascript, html-canvas
---


# Question
Title: Generate a range of number with X being returned most of the time
I am attempting to write a RNG which returns a normal-like curve. For example, say I define X to be 4, I would like to generate a range of numbers from 1 to 8, but with 4 being returned most of the time (say 60%).

How can I accomplish this in a way I can easily define X, and the range of the numbers?

# Answer
> 5 votes
You can easily generate numbers from range \<0,1\> with uniform distribution and then project them to range \<0,2X\> with function like in the graph:

http://filmy.zaachi.com/up\_images/full/graph.png

It's up to you to choose function (it can be for example some trigonometric function or some more sofisticated function which generates normal distribution - like Gaussian function).

If you have generator with normal distribution, just just multiply generated number with 2X.

# Answer
> 3 votes
You can also use the 'ol dice which is a crude way to 'boost' the middle numbers.

1 dice = 1..6 (equal distribution) 2 dices = 2..12 with 7 having a probability of 1/6 (6/36) and 2 a probability of 1/36.

You could also try something like this to simulate that functionnality with any numbers:

```
int getrandom(int start, int stop)
{
int a=stop-start+1;
int r = (rand(a) + rand (a)) / 2;
return(r + start);
}

```

where rand(x) is supposed to return a number from 0 to x-1 (ie rand(5) gives 0 to 4)

You can add the probability for those middle numbers by adding the rand (a) several times ie. :

```
int r = (rand(a) + rand (a)+ rand (a)) / 3;

```

or

```
int steepness=7;
r=0;
for(int i=0;i<steepness;i++;
 r+=rand(a);
r/=steepness;

```

# Answer
> 2 votes
Talking about percentage, you can generate an integer number from 0 to 99 than subdivide your 100% into chunks of different sizes:

```
| 10 | 10 |   20    |      30      |      30      |
   1    5      2            4             3

```

so if random is `[0 10[ => 1;` `[10 20[ => 5;` `[20 40[ => 2` `[40 70[ => 4` `[70 100[ =>5`

this means that you will get 1 and 5 with 10%, 2 with 20%, 3 and 4 with 30%.

This method can be stressed further as @zacharmarz correctly pointed out.

Whichever size you use for your uniform generation, you will arrive to run out resolution so you know that will be points in the curve that you will never reach. Let say that MAXRAND is 1000, you can't newer get results of the curve beween 123 and 124 for example. You can go further by doing another generation so you can subdivide the curve between 123 and 124 in 1000 pieces

here an example with MAXRAND = 6 (!!)

The orange comes from the first extraction and the dark cyan comes from the second one

---
Tags: mathematics, random
---


title: AI engine for iOS game development?

text:
# Question
Title: AI engine for iOS game development?
I'm looking for an AI engine for iOS game development (machine learning, path finding).

# Answer
As @slf commented any C/C++ code can be compiled for iOS devices. so you can use any of these libraries:

1. dlib is a library which has many useful tools including machine learning.
2. MicroPather is a path finder and A\* solver (astar or a-star) written in platform independent C++ that can be easily integrated into existing code.
3. Here is a list of some AI libraries suggested on OGRE3D website. Seems they are mostly written in C++ and at least most of them are not depended on OGRE engine itself.
> 4 votes

---
Tags: ai, ios, objective-c
---


# Question
Title: Cocos2d not getting the texture which is added to CCTextureCache using thread
I convert the image into texture in a thread using the following line of code to reduce the image to texture converting time.

\[\[CCTextureCache sharedTextureCache\] addImage:@"imageName"\];

But when i retrieve this image from cache i am getting a blank image. If i am calling the above line of code in main thread i am getting the image.

# Answer
There is function in `- (void)addImageAsync:(NSString *)filename target:(id)target selector:(SEL)selector` I suggest you either use this function or try reading how this function is using thread.
> 1 votes

---
Tags: cocos2d-iphone, ccsprite
---


# Question
Title: Skipping glReadPixels and reading iPhone's "VRAM" directly
I'd like to rapidly capture "screenshots" of my OpenGL ES iPhone game and turn them into a video. I've tried the following approach (it works but degrades the game play to an unacceptable level):

* Use `glReadPixels` to copy the data from the framebuffer to a `GLubyte` array. Create a `CGImageRef` from that data. Then create a `CVPixelBuffer` from the `CGImageRef`. Finally append the `CVPixelBuffer` to an `AVAssetWriter`.

I've done a fair amount of additional research. Some people suggest copying the framebuffer and reading that piecewise with `glReadPixels`. This could work... but I don't know how to copy a framebuffer. (any help is appreciated!)

I just learned that the iPhone's "VRAM" is really part of the main memory. **How can I read the contents of a framebuffer from "VRAM" without calling `glReadPixels`?**

Hopefully this approach (or similar) will keep the frame rate of the game acceptable.

# Answer
You can't. Only an OpenGL ES Extensions could allow it, but nothing is available. This item is on the Aras wishlist (Unity Engineer).

Why can't you use IOS emulator to do videos ? The emulator is often faster than real devices.
> 3 votes

# Answer
There are a number of ways to accelerate glReadPixels.

Firstly you can experiment with different values for the *format* and *type* parameters - getting these to match the layout of your framebuffer means that glReadPixels can do a direct transfer from the framebuffer; otherwise it will have to round-trip through software to convert from the framebuffer format/type to your specified format/type.

On PC hardware I've personally found that a *format* of GL\_BGRA gives the best performance. On some drivers using a *type* of GL\_UNSIGNED\_INT\_8\_8\_8\_8\_REV (instead of the more commonly seen GL\_UNSIGNED\_BYTE) is also required. It may be the same or may be different for the iPhone so experiment.

Secondly what you do with the resulting data can have an effect. Using an image format of TGA for example means that no further conversions need to happen (if your fastest *format* is GL\_BGR or GL\_BGRA then all the better - you don't need to swap the colour components). Just alloc a buffer of the appropriate size + 18 (which can be a one-time-only op), glReadPixels into &buffer\[18\], then fill in buffer\[0\] to buffer\[17\] with data for a TGA header - done.

10 or so years ago I used this method to export video from a PC game on a TNT2 and was able to get exports at maybe 30 FPS/640x480 resolution (including time spent in an AVI encoder).

Finally, glReadPixels will need to stall the pipeline in order to complete the readback. If you have PBOs available you should be able to read asynchronously into a PBO and avoid this stall. I've personally never used this method though, so can't comment any further on it.
> 3 votes

# Answer
Three answers:

First, figure out where your bottleneck is. You've described a *very* long process there. Where's the slowdown? If the slowdown is glReadPixels itself, then you've got a problem (see second answer). If the slowdown is everything between glReadPixels and AVAssetWriter, maybe you just need a more efficient way of passing it into AVAssetWriter. If the slowdown is AVAssetWriter itself, then maybe you just need a more efficient way of dumping the video to disk.

Second, if the slowdown *is* glReadPixels . . . well, if a much faster approach existed, don't you think glReadPixels would likely use it? It might just be slow. You might just be out of luck.

Third, I know I've seen videos of iPhone games. Contact an indie developer with an iPhone video. Ask them how they did it. Then post the answer here.
> 2 votes

# Answer
If you are just making a demo video then turn your game engine into a rendering engine.

Have a very set time step, no real time involved in this at all. Then instead of rendering the game to the screen, you render each frame to a file.. Now clearly this will require you to be able to script or direct the action that you are trying to capture, but this is a -very- common way demo videos are captured from yet unreleased games.

Again, this may require additional development work to accomplish the scripting aspects of it since you are pretty much removing real time from it.

Hope this helps.
> 1 votes

# Answer
To get the contents of the backbuffer, the fastest way is to render all your scene to an intermediate FBO, save the frame data to a file and draw onscreen.
> 1 votes

---
Tags: opengl-es, ios, optimization, gpu, video
---


# Question
Title: How can I create a game as a live wallpaper?
I have a space shooter game for Android and I want to implement it as a live wallpaper. Any ideas on how this can be done?

Or better yet can anyone help me / provide a template that calls a "ship" object that fires missile? I'll do the rest from there onwards. I just need it as a starting point for learning Android.

# Answer
The first Google hit I got for live wallpaper api android gives a good overview and links to example code.
> 1 votes

---
Tags: android
---


# Question
Title: How do you make a customizable 3D character with animation in iOS?
I want to build a character system in my game that is like the on in Mod Nation Racers or Little Big Planet 2. You have a basic and simple Character (which is animated) and you can now put stuff (cloth, hat, glasses, eyes, mouth) and skins (yellow skin, hairy skin, ...) on it, like a puppet.

(This is all for iPad / iOS with Objective-C)

Does anyone have some url for me to get me started?

# Answer
> 3 votes
In terms of having a character with "attachables", a simple yet effective system is to use named Sockets. This is the system that UDK uses for attaching particles, weapons and equipment to character models.

A "Socket" is a point on the model to which a piece of equipment can be attached. internally, a socket consists of a name (with which it can be referenced), a vertex index (indicating which vertex on the model to position it) and forward- and up-vectors (indicating the orientation of the attachment in question).

Each "Character" then, would consist of the usual model, texture and animation sets, as well as an array of sockets, and an array of attachable equipment. When designing your character, have separate lists of attachables, sifted by which socket they apply to (separate hats from chestpieces, etc).

When rendering, it should be a simple case of render character, then iterate through the attachables and position-\>rotate-\>render each one.

**Update** As DMan reminded me, a socket is usually represented as a bone if the characters are skeletally animated. This handles name, position and animation, and lets you fine-tune the 'socket' in your favourite modelling package (Lightwave for me =D ).

# Answer
> 1 votes
It's not that easy. Since you want it 3d, you will have to make your whole game with OpenGL ES, not just simple 2d cocoa touch frameworks. But before you re-make your game with OpenGL, you will have to learn 3d modeling, animation, cloth simulation, etc.

A word for the wise: **start small.**

I suggest you start with 3d modeling. Check out blender. It's free and open-source.

# Answer
> 0 votes
Fundamentally there's nothing specific to iOS about what you want to accomplish. The high level techniques are going to be the same.

That being said, one easy way to get started is by using Unity. They have a character customization tool that will get you started.

Demo: http://unity3d.com/gallery/hosted-demos/dressingroom.html

Project: http://unity3d.com/support/resources/example-projects/charactercustomization.html

(Note that the streaming of assets through their "asset bundles" system requires Unity Pro, but the concepts should get you started.)

---
Tags: 3d, animation, ios
---


# Question
Title: Should scripts interact with an abstraction of the engine?
I'm using Java and Jython, and after some research I discovered giving scripts direct access to the engine interface could be a mistake, as it would tightly couple the two.

It looks like most scripting that allows mods to create and manage entities does so through some sort of abstraction. Are these abstractions there for this reason, or is it just to provide a more intuitive way for non-programmers to mod the game?

# Answer
Both, in general. Your scripts should talk to an abstracted -- or at least intermediate -- layer of functionality and not the engine itself.

First, this provides you an extra measure of control and security. It allows you to easily, cleanly define the interface a script is allowed to have with your game and thus what it can muck about with, as well as allowing you to place extra security checks in the intermediate later that would not necessarily be appropriate in the actual functionality layer itself.

Second, it allows you to simplify the interface exposed to scripts to be more non-programmer friendly or easier to use in general.

It does provide a bit of insulation against coupling between the two, but it's often not *that* big a deal because the scripts will always be coupled to the interfaces they are allowed to interact with, by their very nature. The other two points are far more beneficial.
> 7 votes

# Answer
I also think that it helps you in case you want to make modifications to the engine. You can do them without worrying about having to change all of your scripts since the engine changed. You just have to change the abstraction layer Josh mentioned.
> 3 votes

# Answer
Creating a layer between the core of the game and the scripts, used for creating modifications is, in my opinion, necessary.

You gain several advantages by using this method:

**Easier for modders:**
A good reason to do this is, as you mentioned, an easier ways to make mods. Writing less lines of code means more readability and minimizes understanding issues for programming newbies. Ideally, this API should be a collection of methods to change something **on the game's high level**. This means for example: Spawn an entity without knowing **how it really gets spawned**, or displaying an image with one call, which only takes the image name as a parameter.
You, as a programmer, also benefit from it, as you can **write more in less time** than you would need with Java.

**Security:**
Preventing people from controlling the whole game is essential. I would not care, if the game would be a single player title, but I would care when the game has got *some* multiplayer action. Even if it is only a highscore table.
Other people are **always** frustrated, when someone wins because of cheating (for example: position changes, more specific: position change and direct flag capping). To prevent players from doing so is your main task here.
Keep in mind, that the cheater can **always** decompile, change the code, recompile and play with this client, so add checks on server side. Generally, the "Security" provided is only another, not 100%-safe option to make life for cheaters harder.
> 1 votes

---
Tags: java, python, scripting
---


# Question
Title: How to get and copy font bitmap from WinGDI to a IDirect3DTexture9?
I want to get the pixels (or other data) for any character of the available fonts and copy/build them into a D3D texture so I could make some cache of text rendering by mapping only the character coords in the d3d texture and other stuff I need to solve (and using ID3DXFont is not an option).

How is this normally achieved? Should I render the GDI font to a GDI bitmap and then copy the opaque bits from the bitmap?

I thought about GDI because I can use the fonts installed in the system that way, but I would also like to know which formats should I consider for storing my own fonts and how these formats work.

# Answer
You can use GetGlyphOutLine() with a format of GGO\_GRAY8\_BITMAP to extract individual character images, along with the metrics that tell you about placement and spacing. Without using those metrics, rendering the bitmaps in the correct position is much more difficult.

Ideally you'd also use data from GetKerningPairs() to improve spacing between characters when rendering.
> 3 votes

# Answer
Vector font formats are super-complicated. Either you're using libfreetype, using WinGDI, or making a simple bitmap font.

I don't know if this is the common solution, but libfreetype is reasonably easy to install and use, and you can then package your font of choice along with your program.

I wouldn't rely on system fonts - you never know when some smartaleck is going to have uninstalled Arial.
> 0 votes

---
Tags: textures, fonts, winapi
---


# Question
Title: Driving Force GT: Force Feedback and Wheel Rotation
I'm diving into the world of game development on PC and have a language agnostic question in regards to controller output.

I have in my possession a *Logitech Driving Force GT*. This particular steering wheel controller has force feedback (aka vibration or rumble) and the ability to turn the wheel through the game.

What are my options for interfacing with this advanced functionality (not the basic axis rotations and button presses)? I've read the DirectInput and xInput documentation with no luck. Is it like a propriety Logitech only API, or as simple as passing information via HID?

Any pointers that will lead me in the right direction would be greatly appreciated!

# Answer
Microsoft advises to use their **Direct Input** API. The following article is from 1998, bit might still apply.

http://www.microsoft.com/msj/0298/force.aspx

MSDN might be a useful starting point, too

http://msdn.microsoft.com/en-us/library/ee416842%28v=vs.85%29.aspx
> 1 votes

---
Tags: controllers, force-feedback
---


# Question
Title: How do you organize your game files and classes?
Although it isn't necessary to exclude things like graphics and audio packages, I'm most interested in the organization of the folders for classes that deal with AI and game state. I'm thinking something like this in Java using packages as the example:

```
import com.rpg.characters;
import com.rpg.characters.antagonist;
import com.rpg.characters.neutral;
import com.rpg.characters.protagonist;
import com.rpg.characters.state;
import com.rpg.gameplay;
import com.rpg.gameplay.engine;
import com.rpg.gameplay.maps;
import com.rpg.weapons;

```

Also, does it make a huge difference between 2d and 3d games?

# Answer
Usually, I start out with one file. Then, as time passes, I would eventually have:

* **Framework**: Math, Random, Utility, Asset, Network, Window, Graphics, Audio, ...
* **Player**: AbstractPlayer, Score, Input, Collision, Reaction, Skill, Inventory, ...
* **Map**: AbstractMap, Area, Town, NPC, ...
* **Enemy**: AbstractEnemy, Creep, Boss, BaseAI, FuzzyAI, ...
* **State**: IntroScreen, MainMenu, LoginScreen, Game, PauseMenu, ...
* **Interface**: Button, Text, InputBox, ...

This is only for the client-side of the game. XML, Lua, Javascript or SQL databases are useful for defining many different things especially different classes of players, maps, NPCs, enemies, items, quests, skills, etc. I like **XML** though, because of its simplicity, and its data can be parsed by any other language.

Game files are usually stored in a package file like ZIP or similar resource. I have a **resource loader** that looks for a file in the package, then if it can't be found, it locates the resource in a directory, or some other place. This allows me to develop quickly.

3D games are no different, but they are **more complex**. They need model loaders, instancing, and must use vertex buffers. They consequently make heavy use of shaders to provide other effects like lightning, bump maps, environment maps, etc.

Most 3D games have a **game engine** backend to do all this for them. For Java, try jMonkeyEngine. For C++, try Ogre3D. For Python, try Panda3D.

In my experience, it is better to hardcode everything whenever you can, unless the feature is specifically required. This allows you to **develop the game faster, and refactor later.**
> 10 votes

# Answer
I believe is a bad idea to have antagonist and neutral and protagonist as different classes, unless your antagonists are multientity spaceships and your protagonists are mages, of course. I agree with Nicol that this is not really language agnostic, and I believe is a really bad idea to try to resume the game architecture like that. Just make a comment in the beginnig of the file or a companion .txt if you want to give insight.

Even so, I would do something like this (following the kiss rules):

```
 // I'm assuming java, this may not be possible if java doesn't like kiss rules
 import com.rpg.characters;
 import com.rpg.engine;
 import com.rpg.maps;
 import com.rpg.weapons;

```

I would recommend that if your language allows this, it probably gives the same insight and it's much easier to work with. Even if I don't have a clue about what language are you using (i'm guessing java from import com.), I would do it this way, and I could leave your approach if I were using a "characters" package that contains lots of character types and you just want 3 of them... but how would you do that? characters.antagonist, characters.neutral, characters.protagonist, characters.two\_faced? or characters.mages? it makes no sense unless your characters package is full of garbage and/or your character objects do not follow some patterns, then you will want to import only the relevant characters and not the garbage code, but that would be sign of a bad design.

Also why a package for states? isn't the state just an integer? does it require a whole package? do you really need to give insight about "there are antagonists in my game" by listing the packages? given that most computer games have antagonists... did you already code all those packages or you are just assuming they would look nice and straighforward that way, if they existed at all?

UPDATE: From your comments and the question edit I wanted to add some things.

There are some coding patterns that are common in game engines but the truth is you can't anticipate by using those patterns if you are not used to them/have experience enough with them, that's also why it's easier to start with a game instead of a game engine. In the package list from your question it's easy to notice that you're overengineering already, but you don't really know how will you code things in there (your package design is overly complicated for no reason).

You can represent most characters with a single class or so, it makes no sense to have such package/namespace distinctions, think about them as if they were an image/texture class, often you don't have pngimage, gifimage, tiffimage, bmpimage etc you just have image.load(), characters could be thought as a resource. They will share most attributes such as position or direction or AI algorithms, you may even want the player to be controlled by the AI at some point, or be able to control an enemy. It makes no sense to have another object for just one function--unless you're using a component architecture for complex game entities, but then they would be components, not characters.

I also disagree with the advice of hardcoding from Roy, you should never hardcode, because it will be harder, specially for an rpg, you have to find a scripting solution that lets you modify game states during runtime for character and item design, or you will be running the whole application every time you want to balance the stats of anything (at the point you will be spending more time running/compiling the app than anything else).

Of course if you must ship fast just put everything in a single file and pray, but otherwise take your time for doing it well.
> 4 votes

# Answer
The truth is that you shouldn't be making this decision at the beginning of a project. My rules of thumb (and trust me, this is very fast and loose) are:

* Things which are obviously different concepts can/should go in different packages
* try to minimize the number of packages you have to reference in any one class ... if you find yourself referencing every single package, you probably have a problem with the way you're expressing your classes. Remember, Single Responsibility Principle.
* Don't be afraid to refactor ... this is the key point here. I usually keep things simple at first and keep everything in a single namespace/package. As the project grows and I find more than a screenful of classes in a single package, it's usually an indication that I may have to refactor.
* Try to avoid deciding on patterns at the outset of a project. Favor working code first, and then as the codebase evolves, refactoring (common theme) to patterns that may emerge from your use cases.

At the end of the day, the most important thing is getting the game working, testable (for early/often playtests), and moving forward towards shipping. Note that I'm not advocating messy, or thoughtless code ... quite the opposite, there are patterns and stuff for a reason. But rarely can one decide those things up front, you will find yourself kludging what you're trying to do into a box, when you need a circle.

Now get out there, and make that game!
> 4 votes

# Answer
A single file to begin with, and split-out into separate files as/if required.
> -1 votes

---
Tags: 2d, 3d, architecture
---


# Question
Title: How can I spawn monsters at random locations?
I made a little 2D shooter game for my iPhone. I want monsters to spawn at random locations. But I don't have any clue where to start to make them spawn.

I already made the monster image and everything and everything works, but there's only one monster at the start of the game and when it dies he will not spawn again.

# Answer
> 2 votes
Here is a thread on StackOverflow discussing random number generation in Objective-C. It's relatively straightforward: whenever it is time for a new monster to spawn, you generate two random numbers in a suitable range (for example, from 0 to the width or height of your playing field) and use those for the monster's initial X and Y location.

You can do whatever you want to determine "when it's time for a new monster to spawn," either by counting down with a timer (so new creatures spawn every five seconds regardless of whether or not the player has killed existing ones), or whatever you want.

It sounds like you're having trouble with the basics of getting the creature to respawn, so you should start with something simple: try checking at the beginning of every game loop if the monster is still alive. If he's not, create him. This should work both the first time the game starts and any subsequent iterations of the loop after the player kills the monster. For example, your code might look like:

```
MyMonster* monster = NULL;

// ...in your main game loop:
if(monster == NULL) {
   monster = /* create new monster */
   monster->X = randomNumberBetween(0, playfield.width);
   monster->Y = randomNumberBetween(0, playfield.height);
}

```

Note that the above is intended to be pseudo-code and will not compile or function exactly as-is. If you have trouble with the respawn, you should probably post another question about it (as it's a different question from picking random locations for a spawn position, and this is a Q&A site, not a forum).

---
Tags: 2d, iphone, game-mechanics, objective-c
---


# Question
Title: How do I extend Irrlichts scene manager?
If I want to extend the scene manager, and add a function; do I extend my class from `CSceneManager` or `ISceneManager`?

I'm trying this in `MySceneManager.h`:

```
#include <CSceneManager.h>

class RTSSceneManager : public CSceneManager
{
    virtual ICameraSceneNode* addCameraSceneNodeRTS(ISceneNode* parent = 0,
            const core::vector3df& position = core::vector3df(0,0,0),
            const core::vector3df& lookat = core::vector3df(0,0,100),
            s32 id=-1, bool makeActive=true) = 0;
};

```

But it's giving me this error:

```
fatal error C1083: Cannot open include file: 'CSceneManager.h': No such file or directory

```

It works if I use `ISceneManager` instead of `CSceneManager`, but then won't I have to re implement `CSceneManager` over again?

# Answer
You don't need to extend the scene manager nor the camera(like you said you need modify the engine itself for that). Just add an animator, extend from ISceneNodeAnimatorCameraFPS.h or ISceneNodeAnimatorCameraMaya.h and implement it's functions, instead of extending from the camera and having to extend the numerous functions it has.
> 3 votes

# Answer
That error is just because either you're not setting the right path for the SceneManager headers (wherever CSceneManager.h is located), or you do but you're using \<\> instead of "" in the #include line. It has nothing to do with the inheritance, it should fail either you use CSceneManager or ISceneManager, because you're not including the header properly (or at least that's what the error is saying).

For extending the scene manager you must derive from CSceneManager, as ISceneManager is just an pure virtual interface with no function definitions. Note the `=0` at the end of the function declarations in the ISceneManager class, that means the function has a null definition which the implementation class must overload to comply with the interface declaration. If you do derive directly from ISceneManager, you must provide an implementation for every pure virtual function it declares.
> 3 votes

---
Tags: irrlicht
---


title: Game engine and data driven design

text:
# Question
Title: Game engine and data driven design
I've heard about data driven design and have been researching about it for a while. So, I've read several articles to get the concepts.

One of the article is Data Driven Design written by Kyle Wilson. As he described, it seems to me that the application code (i.e. the code for controlling resources such as memory, network...) and the game logic code should be separated, and the game logic code should be driven by external data sources. At this point, I can imagine that the developer would write some sort of game editor which accepts external data about in-game objects (such as character information, weapon information, map information...). The scenario design will be scripted by custom language/tool written by programmer to let the game designer create interaction between in game objects. The game designer will either use an existing/custom scripting language to write script for the game, or drag and drop tool to create game world. Example of tool approach I can think of is World Editor, which usually packaged along with Bliizard's games.

However, another article is against the use of Data Driven Design, The Case Against Data Driven Design. The author suggests to not let the game design driven by data, because it would take more time to develop a game, since the game designer has the burden of programming. Instead, there will be a game programmer to program the game freely from the sketch design, and is verified by the game designer after the game programming is finished. He calls this is programmer driven. What I think of this method is similar to the way I used to do: The game logic is the application itself, as apposed to the above idea, the application is the game editor, and the actual game is designed based on the tool.

To me, the first method seems to be more reasonable, since game components can be reused for many projects. With the second method which opposes data driven design, the game code belongs to that game only. This is why I think Warcraft has so many game genres in it, such as the original Warcraft and various custom maps, and one of the most famous: DOTA which actually defines a new genre. For this reason, I heard people call the World Editor is the game engine. Is this true how a game engine should be?

So, after all of this, I just want to verify that is there any flaw in my understanding about these ideas (data driven, programmer drive, scripting etc...)?

# Answer
> 30 votes
Making your game (or any software product) data driven is almost always a benefit. The only real con is that you may spend slightly more time building the relevant systems up front; it will pay off over the rest of your career as a programmer though (even if you don't reuse those same systems for that entire time, you'll reuse the techniques you employed to build them).

The challenge, and where the disconnect in those two articles you linked comes in to play, is *what* you elect to put in data and *who* you elect to give access to that data. Fundamentally, data driven design and development just means that you put information in external storage, load that information at run time, and act on it. Your application code does what that external data tells it to, rather than you writing application code that directly does what you think the end result should be. It's not a complex idea.

You don't have to build complex "component driven architectures" (as is the fad these days). Putting constants for tweaking physics (gravitational force, restitution coefficients) in a text file is data driven. Scripts (in Lua or something else) are data driven. Describing your level data in XML. Anything like that.

You can drive just about any component of software with data, and you can pick and choose which ones you want to do so with. Developer time is expensive; programmer time especially so. If you can save you or other programmers time by putting behavior and data in external storage and not requiring the game to be recompiled for every little change, you should. You'll save money and get things done faster.

Furthermore, you run a huge risk in attempting to make "designers design" and having programmers "make those designs a reality," forcing a programmer to exist in the iteration loop for a designer's job: you run the risk of making the programmer feel like he is just a code monkey, making trivial little tweaks for the design constantly. This can be massively demoralizing for a large majority of programmers, who want to work on interesting technical challenges and not on being a designer's proxy.

For your specific questions:

> Is this true how a game engine should be?

A "game engine" doesn't really have a fixed definition. Generally it's the unified collection of underlying technology used to make a game, usually supported by a bunch of related tools (and thus quite data driven). But it varies fairly widely from context to context.

> So, after all of this, I just want to verify that is there any flaw in my understanding about these ideas (data driven, programmer drive, scripting etc...)?

You seem to be more or less on the right course, although you're perhaps over-complicating what data driven design and development is by conflating it with component-based systems.

# Answer
> 7 votes
As the author of the second post, I would like to clarify a few points.

1. As Josh Petrie suggested, structuring your code to use data instead of just hard coding everything is always a win. I wasn't suggesting otherwise. I was pointing out that pushing everything on the designer is not a good idea. The term "data driven design" means different things to different people, so I probably should have been more specific when I wrote the original article.
2. At every place I've worked, we create data structures that are tweakable in engine. To make a change, we don't have to recompile the game. We can change the number dynamically at runtime. The data structures are often stored in code, but depending on who is changing them, they can easily be loaded from a "data file".
3. Most development environments support some form of edit and continue or module reload for C/C++.
4. Most game development studios have gameplay programmers. Their jobs is often to work with the designer in creating a fun experience. Their main concern is not technical challenges but rather crafting fun from code. I have worked as a gameplay programmer for many years, and I find this more interesting than just trying to solve technical challenges. My responsibilities have varied, but I have found my work most fulfilling when I am in charge of the implementation and I work with the designers on crafting something cool. The problem with designers coding or scripting is that programmers often have to sort out the bugs, which is one of the least fun things you can do as a programmer.
5. What works best for a studio depends on the game. If you have a long time to make a game, and you want to give your game legs for the mod community and create something huge in scope, then making a game that is completely data driven makes sense. A lot of games don't have that goal. They have to churn out a new game in two years, and unless they have a hit franchise, it is probably a different type of game than their previous work
6. What a "designer" does can vary from studio to studio. I've heard of a development studio that hires gameplay programmers from other studios, calls them designers, and has them script the game behavior. This sidesteps the problem of having people who aren't trained in programming coding/scripting.
7. There should always be a delineation between game logic code and engine code. As well, you normally want to have some sort of visual editor for object placement. I've never worked at a studio where enemy locations are hard coded. They are placed in an editor. Let me propose an example of what I'm talking about. Let's say the designer thinks up an enemy. Does the designer than script the behavior of this new enemy type? That is what I consider data driven design (in terms of what Tim Moss wrote about it). In the way I am proposing, the programmer works with the designer, they make a fun enemy together perhaps with tweakable parameters, and then they are placed in the level.
8. Native code written by a programmer is going to execute faster at runtime than a script written by a programmer, which will execute faster than a script written by someone with less technical savvy. This performance may or may not be important depending on what type of game you are making and what you are doing, but it is something to consider.
9. You can share game code between games regardless of what method you choose. I'm not really sure what you are getting at with this point. Even if you aren't using a scripting language or visual tool to define some behaviors, you should be architecting your gameplay code into reusable components as much as you can. There will always be stuff that isn't applicable to your next game, but every place I've ever worked at, when we start the next game, we start with the codebase from the previous - even if it isn't a sequel. We then keep the stuff that makes sense and remove the game specific stuff.

In the end, there isn't a right or a wrong answer. It's a question of how you and your coworkers are comfortable working. When I wrote that blog a while back, there was a lot of talk about how all the work should be pushed to the designers, and I wanted to write about how plenty of successful game companies that I knew of found a different balance.

Also, as a side note, my blog entry is 5 years old. It seems like a lot more studios are moving towards scripting languages and whatnot these days but are creating mature tools for debugging them, which was my main complaint. When I had written this, I don't think Unreal Kismet existed, which I haven't used, but it seems like they are trying to simplify scripting and it apparently has a debugger. (No idea how well it works though)

For smaller scale games, I definitely don't think you want to try and roll in a scripting language or similar functionality into your tech, but if you have a huge team and a lot of time to devote to technology, it's possible to do this right and the time investment may make sense depending on the way your development team likes to work. Personally, I will probably cling to C++ for as long as possible because for me, it's the easiest and fastest since I often have to try and work around "features" like garbage collection.

# Answer
> 2 votes
You should look the BitSquid Tech Engine. It is build using DOD concepts. The blog of Niklas Frykholm is very interesting. There are many articles on how this engine is designed.

At the GDC 2011, Niklas has made a presentation about Data Driven Renderer.

---
Tags: architecture, data-driven
---


title: Variable physics step, bad idea?

text:
# Question
Title: Variable physics step, bad idea?
Currently, when I update the entities I calculate the time passed since the last update, and then pass that to their update function. They will in turn pass that duration to all their components.

```
    currentTime = clock.getTime()
    timePassed = currentTime - lastUpdate

```

This means that the physics components also gets a variable time step, but it appears this is bad and can lead to inconsistent simulations. Here's some details on this:

\> When should I use a fixed or variable time step?

The answers suggest that the physics simulation time step should be constant and higher than the rendering time step. But since I can't ensure how well the game will perform, this can be rather difficult to achieve.

One answer suggests this:

> Use Gaffer's "fix your time step" approach. Update the game in fixed steps as in option 1, but do so multiple times per frame rendered - based on how much time has elapsed - so that the game logic keeps up with real time, while remaining in discrete steps.

This seems like a good approach to me, but I don't really understand how I should be doing it. Instead of doing:

```
physics.step(timePassed)

```

I should be doing the following?

```
while timePassed > 0:
     physics.step(1) # millisecond
     timePassed -= 1

```

# Answer
The problem with the physic simulations lays on the integration step to solve equation of motion.

What you should do is simply to set an error in integration you can accept (ε) then look to your integration algorithm to see for what step size it gives you that error (ε(Δt)); let say that this error is Tmin.

Now if your elapsed time is less than Tmin a simple step may suffice; if is greater you have to split it in *n* substeps where each substep is less than Tmin (n = floor(elapsed / tmin); substep = elapsed / n).

Now everything is related to your ε: greather ε means more integration error but less iterations; little ε assures you both a better precision and more iterations.

Please keep in mind that integration errors sums up so your motion trajectory will diverge from the real one (more if the system is badly conditioned).
> 4 votes

# Answer
With physical simulations, you don't want to vary the time rate because what you most likely are using is a "Discrete" solver. What this means, is that it ignores the between state of objects between each "step". Sub-stepping and sweeping to check for tunneling also fall under the Discrete Solver umbrella.

Variable time-steps can only be faithfully used in simulations that use a "Continuous Solver", which involves extremely high-end mathematics and can't be used for real-time applications, games for instance.

For a Discrete Solver, think of time as flowing in chunks. It only advances when you call the "step" function. If you call `step()` 60 times a second, then time flows forward 60 chunks in one second of our time. If you call `step()` only 30 times per second, it advances only 30 chunks, and from our perspective it appears to be half as fast. But within the simulation, it does not see that.

If you vary the time between frames in the way you describe, what you are doing is actually causing the 'chunks' of time to become larger and smaller arbitrarily. It would be as though time in our reality got choppier then smoother, and it'd cause all sorts of problems for us.

As for how to set up the timestep, assuming you want the framerate to be 60...

```
int last_time = 0;
int recent_time = 0;
int times_executed = 0;
float time_step = 1000.0 / 60.0;
// ...

last_time = recent_time;
times_executed = 0;
recent_time = getTimeInMS();
while(recent_time + (times_executed * time_step) < last_time + time_step){
    physics.step(time_step);
    times_executed += 1;
}

```

I haven't tested the above but it may help you get started
> 1 votes

---
Tags: physics, simulations, fixed-timestep
---


# Question
Title: How to handle multiple story threads in a RPG game?
I designed an RPG game that has multiple story threads, meaning that, depending on the user's choice some things may or may not happen, you can achieve the same thing in several ways, the ending can be different and so on.

I implemented a simple decision engine, which works fine but has one huge flaw, in the moment you take a decision the story is influenced immediately by your decision, which means that you can't take a decision that will affect you in the far future. This is because the story unfolds like a branch in a tree structure, and it always needs to know which node is next. Under the hood, the decisions are implemented using a queue: each node knows about the previous node and the next node (or if it's a decision node it waits for user input to set the next node)

I saw lots of games that have complex decision engines, and I wonder, how are they made? Is there a special design that makes the things really easy? Did anyone did something similar and can give me a hint on how to tackle this?

UPDATE 1:

An important aspect is to manage to somehow keep the story code independent, so that it can be manipulated from an external file. I plan to use this as an engine so even the possible choices have to come from an external file. The code has to be totally abstract.

Also, I'm interested in a design solution, a nice way to do it, how others do it or did it.

# Answer
> 18 votes
You could also generalize the queue into a directed acyclic graph (DAG). You can read about these on Wikipedia. Basically, each node can have one or more parent nodes that it "depends on". Cycles aren't allowed, i.e. if A depends on B, B can't depend on A (directly or via any indirect chain of other nodes).

Each node is in an "active" or "inactive" state, and is only allowed to become active if all its parents are already active. The structure of the graph (what nodes are there and how are they connected) is part of the game data, but the active/inactive state is part of the player's save data.

That way, you can model things like: when you plant a tree, you mark a task "plantedTree" as active; then, later on in the game, another task "treeGrown" names both "plantedTree" and some other node (part of the story) as its parents. Then, "treeGrown" only comes active when the player gets to that point in the story, and also "plantedTree" is active.

You can include other features such as nodes that activate if any one of their parents activates, or nodes that are activated by one parent and deactivated by another, and so on. It's a pretty general framework for creating stories with multiple, interdependent threads.

# Answer
> 3 votes
From what I understand, what you want is not just a decision engine, but a rule engine as well. For each decision you execute a subset of rules defined by that decision. The execution of those rules is often dependent on the state of certain entities like your tree example.

Basically, when your player makes a decision you search for that decision, execute the rules, and then provide the next set of available decisions like normal. However, your rules are dynamic in that some of them will only execute based upon other rules that have already executed.

Some more on Wikipedia.

From their **When To Use Rule Engines** subheading (emphasis is mine):

* The problem is just too complex for traditional code.
* The problem may not be complex, but you can't see a robust way of building it.
* The problem is beyond any obvious algorithm based solution.
* It is a complex problem to solve. There are no obvious traditional solutions or the problem isn't fully understood.
* The logic changes often
* ***The logic itself may be simple but the rules change quite often.*** In many organizations software releases are rare and rules can help provide the "agility" that is needed and expected in a reasonably safe way.
* Domain experts and business analysts are readily available, but are nontechnical.
* Domain experts are often a wealth of knowledge about business rules and processes. They typically are nontechnical, but can be very logical. Rules can allow them to express the logic in their own terms. Of course, they still have to think critically and be capable of logical thinking. Many people in nontechnical positions do not have training in formal logic, so be careful and work with them. By codifying business knowledge in rules, you will often expose holes in the way the business rules and processes are currently understood.

One thing to note is that occasionally a rules engine is best implemented using a simplified domain specific "language", or something like YAML. I would not suggest XML.

# Answer
> 1 votes
You have to consider that an event is not purely based on user decision. As you noted some event has to append if when a set of decisions sequences are taken *and* then something else appends (like two day after).

What I think you need is a way to model events and way to trigger it. While the first is more bounded to your specific case, the latter can be modeled by an hierarchical state machine (HSM) that directly or indirectly triggers your events.

Keep in mind that a state machine suffers of the Curse of dimensionality that is only mitigated by an hierarchical structure. Soon you will understand that you need to model the complex meaning of status using a HMS but also provide a way to query it.

In this scenario you have basic events (user decisions, time, change in weather and so on) that are processed by both the HSM and by basic event callbacks. The HSM provide a model for the "memory" and the callbacks provide a way to describe how that memory has to be used to compute the consequences of a sequences of decisions/external events.

You may also end up in using a dictonary (or some other collection structure) of HMS, one for each "aspect" of status you have to compute. An example may be to use an HMS event related and one for the decisions that callbacks take in order to trigger events.

All this infrastructure serves the purpose to mimic the behavior of a human Dungeon Master: he generally takes a mental record of the current situation (HMS\["external"\]) due to player decisions and environmental conditions; when something appends it can take decisions using its mental record and record some internal strategy status too (HSM\["internal"\]) in order to avoid to react in a similar way if the some situation appends for example.

---
Tags: architecture, rpg
---


title: Shapes and sprites in SVGs

text:
# Question
Title: Shapes and sprites in SVGs
I understand SGV images are used in 2D games to store shape data for the physics engine of the game. I'm unsure though, should the raster sprite also be stored in the SVG or should it be separate?

Also, what about animated sprites? In a non-skeletal-based animation system, how should the shape of the character be handled? Is a simple rectangle enough?

# Answer
SVG is probably not the optimal choice for shape data. The coordinates usually don't align with the ones from the physics engine and require conversion (that's not really hard to do, but you'll have to do it). In addition you'll have to write a special parser to get the shapes out from the SVG file and also make sure all your polygons are actually convex (eg. convert/split concave polygons).

If you plan on using SVG nevertheless, I suggest you just use it for the shape. Your raster image should be packed to a sprite-sheet instead.

There's a specialized tool called PhysicsEditor that can be used to create collision shapes from your raster images. It will make sure your exported polygons are split into convex polygons if necessary. It also allows exporting for different engines.

When it comes to animated sprites: In most cases, you won't need a collision shape for every frame, but rather one that encloses all animation frames. For a player character it might be enough to just have an enclosing circle or rounded rectangle as collision shape. Maybe with additional sensor shapes if needed (front, bottom, top etc.)
> 4 votes

---
Tags: physics, animation, svg
---


# Question
Title: How can I track a falling ball with a camera?
I have been trying to get my camera to follow a falling ball but with no success.

here is the code

```
        float cameraY = (FrustumHeight / 2)+((ball.getPosition().y) /2) - (FrustumHeight /2);
        if (cameraY <  FrustumHeight/2 )
            cameraY =  FrustumHeight/2;
        camera.position.set(0f,cameraY, 0f);
        Gdx.app.log("test",camera.position.toString());
        camera.update();
        camera.apply(Gdx.gl10);
        batch.setProjectionMatrix(camera.combined);

        batch.begin();
        batch.draw(backgroundRegion, camera.position.x - FrustumWidth / 2,
 -cameraY - (FrustumHeight/2) , 320, 480);
        batch.draw(ballTexture, (camera.position.x - FrustumWidth / 2) + ball.getPosition().x,-cameraY + ball.getPosition().y - (FrustumHeight/2)  ,
                32, 32);

```

I'm sure I am doing this completely wrong - what is the correct way to do this?

# Answer
The following part of code is why your camera did not follow along with the falling ball:

```
 cameraY + ball.getPosition().y - (FrustumHeight/2)

```

(In the last line) Since your `cameraY` is already at the Y-ball position, you are basically setting this to a constant factor, making your Ball stationary, yet your Camera moving. Most likely the source of your error.

Hint: you shouldn't be adding and then subtracting the same amount in the first line.

Perhaps, a short description of what is actually happening (how the Camera behaves, etc) would be interesting.
> 5 votes

---
Tags: camera, libgdx
---


title: XNA game randomly drops to 40fps

text:
# Question
Title: XNA game randomly drops to 40fps
I have a fairly straight forward 2D game written in XNA. I'm finding that it arbitrarily drops from 60fps to 40fps.

I've tested this drop extensively and have concluded it's not related to graphics or the hardware being taxed. What's even stranger is that if I put the window in and out of focus a few times the fps jumps back up to 60.

Sometimes the game load sup at 60fps then I put the window out of focus and back in and it drops to 40fps. This happens anytime, including in the main menu where nothing besides two sprites are being drawn, I've even removed rendering of all sprites just to be sure and it STILL happens, so just a black screen with nothing besides a graphics device clearing the screen.

And before anyone asks, yes, I've manually polled my own functions and have found that everything is being updated and drawn very quickly, it just seems that XNA is taking its sweet time to actually call the update/draw functions.

Does this sound familiar to anyone?

# Answer
Not sure it's related but I've had a similar problem once, a really weird one where the framerate simply drops and stays low on what seems to be random runs - like every other debug session or after/before switching between fullscreen modes.

It went away when I disabled fixed timestep which didn't feel like a good solution, but it helped and I never really researched why or what the change actually did as that project used the FRB engine.

This article explains it rather well: Understanding GameTime

```
        IsFixedTimeStep = false;

```

Tinkering with (changing the default) TargetElapsedTime instead might also help with stuttering and uneven frame rates.
> 3 votes

# Answer
That's the expected behaviour. When you put your window in the background, it automatically gets lower priority, thus having a slower update cycle and lowering the framerate.
> 0 votes

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


# Question
Title: Why do Pool.Default D3D volume textures take memory from my process?
I am working on a Direct3D rendering application that uses a lot of texture RAM. I notice that if I allocate a Pool.Default volume texture:

```
   _texture = new VolumeTexture(device, size.Width, size.Height, size.Depth, 1, Usage.None, Format.L16, Pool.Default);

```

my process's **system memory** decreases by the same amount I allocate on the video card. I think this is unexpected. This texture is supposed to be video-memory only.

Effectively this means I can not use all texture RAM on high end video cards, I can not afford to lose a whole gigabyte of system RAM. We're short on adress space as it is....

Is there anybody who knows what's happening here? Are there ways to prevent this from happening?

This was seen on Windows 7 64 bit from a 32 bit process, using Directx 9c, with several different nVidia cards. The process is marked as /LARGEADRESSAWARE to make sure we get as much as adress space as possible.

You may have guessed by now that I am not writing a game.... but I assume the Direct3D experts are here to be found.... And I can imagine this issue affects games as much as it affects us...

**EDIT:**

This appears to happen only with Volume Textures. If I allocate 2D textures of the same size it does not happen. By default my volume textures were 32megabytes each. If I make them smaller (I tried down to 2megabytes each), There are still blocks being allocated. According to VMMap, each texture gets a 32 meg block in my process, flagged as "Read/Write/WriteCombine".

The fact that they are labeled as "WriteCombine" makes me really curious, no other block of memory is labeled like that.

# Answer
> 4 votes
Specifying the default pool does not instruct Direct3D to put the resource on the GPU. It instructs Direct3D to put the resource in the best pool for the usage you specified for the resource.

The task manager is a very poor way of measuring performance, in general. It's possible the allocation is transient and done by the D3D API in order to transfer some data to or from the card (as allocation of default pool resources can evict managed pool resources as needed to satisfy the request).

Also note that on Windows 7, you'll be using the WDDM which can virtualize GPU memory (although generally I think you shouldn't see issues with this unless you are using the \*Ex variant of the device, which I don't believe Managed DirectX can create).

---
Tags: textures, directx9, slimdx
---


# Question
Title: Creating a Game Engine with a C++ Compiler?
I'm thinking of creating a Game Engine with a C++ Compiler using OpenGL but I don't know how to create a compiler in an application. Do I have to write the compiler? or could I use (for example) the Visual C++ Compiler?

# Answer
> 6 votes
The only reason that I can see for including a compiler in an application is that you wish users to be able to write their own code in C++ which is compiled, linked, and executed at runtime. This isn't a brilliant idea, and in fact there is a common game engine technique called scripting that allows users to do write their own code and have it executed.

A short extract from Jason Gregory's Game Engine Architecture (third edition) from page 794 can be found below:

> A scripting language can be defined as a programming language whose primary purpose is to permit users to control and customise the behaviour of a software application.

...

> In the context of game engines, a scripting language is a high level, relatively easy-to-use programming language that provides its users with convenient access to most of the commonly used features of the engine. As such, a scripting language can be used by programmers and non-programmers alike to develop a new game or to customise - or "mod" - an existing game.

A short list of benefits of scripting:

* You can only expose the parts of the engine to the scripting system that you want to.
* The scripts are loaded at runtime and can be edited off-line without the engine needing to be recompiled.
* They help support rapid iteration times and are sometimes quite lightweight.

I would suggest you look into adding scripting functionality as this would be a better solution to your problem. There are many scripting related questions on gamedev.stackexchange to get you started!

# Answer
> 2 votes
Yes, you can (and in my opinion should!) use the Visual C++ compiler. It is currently one of the best compilers out there.

Furthermore, while it is very interesting to write your own compiler, it's not very wise to use it for speed-critical applications like games.

---
Tags: opengl
---


# Question
Title: XNA 3rd Person Camera - pitch reverses when facing backwards?
I have a 3rd person camera which rotates around the Y axis fine (yaw) and when I am facing forward (0, 0, -1) moving the mouse up moves the camera up and down great. But the more I turn the player and camera the the less the camera moves up and down until I get to 90 degrees where it almost stay still and at 180 it moving the mouse up moves the camera down!

Any ideas? How should I be calculating camera pitch? The player only yaws - it does not roll or pitch. The camera yaws and pitches. The cameras update method looks like:

```
    public void Update(Vector3 playerPos, float pitch, float yaw)
    {
        Matrix rotation     = Matrix.CreateRotationY(yaw) * Matrix.CreateRotationX(pitch);
        Vector3 newOffset   = Vector3.Transform(offsetAmount, rotation);

        cameraPos   = playerPos + newOffset;
        View        = Matrix.CreateLookAt(cameraPos, playerPos, Vector3.Up);
        Projection  = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Constants.AspectRatio, Constants.NearClip, Constants.FarClip);
    }

```

# Answer
> 5 votes
Sounds alot like your Matrices are being multiplied in the wrong order. Try reversing the order of Multiplication to:

> Matrix rotation = Matrix.CreateRotationX(pitch) * Matrix.CreateRotationY(yaw);

---
Tags: xna, camera, third-person-view
---


# Question
Title: Converting a Flash animation to Silverlight
I recently had an animated logo done in Flash for Deen Games. I need to display in all my Silverlight games. The problem is, the logo is about ~8 seconds long (205 frames); if I export all the images as even JPEGs, the result is almost 3.5MB of content (more than the game itself).

I tried exporting as various formats (PNG, JPG, GIF, etc.) but nothing is small enough. What are my options? How can I incorporate these into my game without blowing up the file size?

There's always the option of "recreate it in-game with animation/rotation/etc. as it is now) but that's tons of work and I'd rather avoid that.

And no, just a static image is not good enough!

**Edit:** Exporting as a movie (AVI, MPEG) won't work since XNA doesn't support movies at this time.

# Answer
> 0 votes
Flash SWFs are small because graphics are vector and only animation diffs are stored. What this means is that you should **recreate your animation in your platform.** Anything else will requier redundant storage and a huge file-size.

# Answer
> 5 votes
You can export them as a series of images (I would recommend the highest quality you can), compress them into a video file and import the video file into Silverlight. I believe this will have a smaller size than the set of images, especially if you choose a good encoder (like x264).

# Answer
> 2 votes
There's at least one application that claims to do this:

SilverX

I haven't used this so I don't know how good or cost effective it is. However, as you've only got one animation to convert it might be good enough for a short term solution.

---
Tags: xna, silverlight, compression
---


# Question
Title: Using a GLSL fragment shader to draw a texture in the middle of a quad
I'm not sure how possible this is, but I'm trying to use a fragment shader to draw a portion of a texture in the middle of a quad. This is all 2D. The quads consist of four vertices from (0, 0) to (width, height). The modelview matrix is transformed to position the quads.

I have a sprite sheet of 32x32 icons and a 32x32 quad that one of the icons is mapped to. In a vertex shader, I'm creating a 2 pixel 'border' around the quad by moving it's vertices out by 2 pixels. In a fragment shader, I want to display the texture with it's original size, in it's original position; basically, there should be no visible difference between the original 32x32 quad and the 36x36 quad. The result should be an invisible 'border'.

The only solution I can come up with is calculating the window coordinate for the corner of the quad in the vertex shader, then passing it to the fragment shader and subtracting it from gl\_FragCoord, in order to get the position of each pixel relative to the corner of the quad. With this information, I can display the texture in the center of the quad, with it's original size.

Is there any easier way to accomplish this?

# Answer
> 3 votes
I can't try it out right now, but try this:

In the vertex shader take the value of `gl_VertexID` and give it to the fragment shader in a flat attribute (flat so it doesn't interpolate). Also push the untransformed vertex, also flat, and the interpolated but untransformed vertex (non-flat) to the fragment shader.

In the fragment shader look at the value of the vertex id attribute. You can possibly find out in which corner of the quad you are by looking at this value. Then you can use a simple `if` discard the border frames:

```
if(vertexIDAttribute indicates that we are in the top left corner
   && interpolatedVertex.x < uninterpolatedVertex.x + 2
   && interpolatedVertex.y < uninterpolatedVertex.y + 2

   || vertexIDAttribute indicates that we are in the top right corner
   && interpolatedVertex.x > uininterpolatedVertex.x - 2
   && interpolatedVertex.y < uninterpolatedVertex.y + 2
   // etc
) {
    discard;
} else {
    render the fragment
}

```

(old answer is below for history)

---

One solution I can think of is to calculate the ratio of the size of the bordered quad by the size of the unbordered quad and transform the texture matrix accordingly. For example,

```
// quadSize would be 32 in your case
float border = 2.0f;
float scale = (quadSize + border) / quadSize;

glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glScalef(scale, scale, 1.0f);
glTranslatef(-border/2, -border/2, 0.0f);
glMatrixMode(GL_MODELVIEW);

```

(You should store that matrix somewhere so you don't have to calculate it every frame. You can also precalcuate it if the border size stays the same.)

This scales and positions the texture correctly. However, this leaves a 2px size border around the texture, which you can easily discard in your fragment shader. Simply export an uniform describing the quad rectangle and check if the fragment is in the "border". If yes, discard the fragment, else render it just like you did before.

**Edit:** Copy/Paste mess up, it should be `(quadSize+border) / quadSize`, not vice-versa.

# Answer
> 0 votes
Presumably the simplest way to do this would be to leave the sprite alone, and make the border out of 4 additional quads that you add around the edges.

However, if you can't add additional quads, you should be able to do this by manipulating the UVs of the quad. When you push the vertices out by two pixels, also push the UVs out by two pixels as well.

If your sprites are packed together very tightly, this could cause problems with neighboring sprites in the sheet becoming visible in the borders. You could fix this up in the shader by storing the original UV rectangle (before the 2px expansion) and sending it down to the fragment shader. Then check to see whether the interpolated expanded UVs fall outside this rectangle, and if so, discard the pixel (or replace the color with black, or whatever you want to do in the border). This'll make the shader more expensive, of course.

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


# Question
Title: Need help implementing shadows on platform with limited feature set
I am writing a game that very much relies on real-time shadowing and would like to implement shadow volumes. I was thinking of doing shadow mapping, but the platform I am using is Molehill/Stage3D and it's limited to 8 bits per channel, BGRA textures, and shaders can only read from textures, not depth buffers. I have never done stencil shadows before, but would it be possible to generate a shadow volume entirely on the GPU without the use of Geometry shaders, and only vertex shaders?

# Answer
> 2 votes
Is there any way of pretending that a depth buffer is a BGRA texture (by creating a texture that overlaps the depth buffer in memory, maybe), or will the API not allow that? If it will, you can decode the depth value in the pixel shader by working out which three channels contain the depth value, which ones are the high/middle/low bytes of the value, and doing something like:

```
float depth = (highByte * (255.0 * 65536.0) + middleByte * (255.0 * 256.0) + lowByte * 255.0) / 16777215.0

```

(Here, I'm assuming `highByte`, `middleByte`, and `lowByte` are in the 0-1 range, and `depth` also comes out in the 0-1 range.)

Anyway, if that's not an option, you can certainly do stencil shadows - they were invented a long time before geometry shaders existed. However, you will either have to do some expensive CPU work to generate the silhouette edges and project them, OR preprocess the mesh to add additional vertices that can then be projected by a vertex shader. See this article for the details (in the section "Shadow Volumes Powered By Vertex Shaders").

---
Tags: flash, shadows, molehill
---


# Question
Title: What language was used to make Jetpack Joyride?
As I'm interested in creating games like Jetpack Joyride for mobile devices and so on, I wanted to know what technology was used to create the game.

Was it made in Objective-C, Java, Flash or HTML5 canvas/javascript?

# Answer
There are some options to release a game for both iOS and android:

1. develop your game using c/c++ and use a wrapper for some iOS/android specific functions
2. use GameEngines, they can be either native code like cocos2d-x (which is again c++) or scripting languages like Unity or Shiva3D
3. develop your game two times once using Obj-C for iOS and once using Java for Android.

Each of these ways has their own advantages and weaknesses. But I suggest you use one of existing gameengines, either cocos2d-x (if you are a coder by nature) or Unity (if you are a designer)
> 4 votes

# Answer
To answer your question directly, Jetpack Joyride was made in Objective-C, with possibly a few areas of low level being C++ (and OpenGL for 3d hardware interaction).

You cannot make Java apps on iOS (not without jailbreaking).

HTML5 apps are not available from the App Store.

iOS does not run Flash, though Adobe do provide the capabilities for Adobe Air/Flex apps to be compiled into a native iOS app, the effect this has on performance is often noticeable, and I've yet to see a notable studio develop anything significant using that technology (not mature enough at this point).

As a quick tip, any game that uses GameCenter HAS to use Objective-C.
> 3 votes

# Answer
the iPhone apps you can download from the appstore are made in Objective-C. For the Android platform, the main language for creating apps is Java.

Over that, there are frameworks that simplify the programmation and makes it multi-platform(iOS/Android) such as Titanium and others, but i don't have the names in mind.
> 1 votes

---
Tags: android, iphone, mobile
---


# Question
Title: Are mobile devices a viable platform/market for "User-Generated Content"-based games?
I intend to do a lot of research into this, but I know this community has a knack for delivering hard-to-find gems of knowledge, so I figured I'd ask here first.

### Preamble (My Situation)

I'm currently looking into the viability of becoming an independent games developer by selling games for the mobile platforms (iOS and WP7 in particular). However, as I currently work full-time, all development has to be done in my own time (weekends, after-work, early mornings). Thus, I need to be careful with how I spend my time (I also have a social life to maintain). Basically, if I can release something that makes enough money, relative to my time investment into it, to be able to support myself with, I'll seriously consider taking the plunge.

### The Question

One of the ideas I've had is for a game in a similar vein to Little Big Planet or Kodu, where the focus is on user-generated content, with the game itself providing a set of tools, samples and access to a 'market' for user-content.

What I envision is a simple set of drag and drop tools for placing content in levels, customising template assets, etc, and node-based editors for behaviour and logic (Think along the lines of Kismet, for those of you familiar with the Unreal Engine).

As a programmer, I've looked into this enough to know it is possible from a technical standpoint. However, what I need to know is if it is viable in terms of userbase. Is there a market for user-generated content games on the various mobile platforms?

Just to clarify, I'm **not asking how** to do it, I'm asking **if it's worthwhile** to do it.

**EDIT**
To reword the question and make it more answerable (given the lack of existing examples), what are relevant design considerations typically associated with the psychology of the mobile gamer that would influence the success of a game based on user-generated content?

**EDIT 2**
Microsoft have just released an app for WP7 called TouchDevelop that allows users to write executable scripts using a simplified tile-based interface. It's been downloaded a lot and garnered positive reviews. So, that's as strong of an indicator of community interest as I figure I'm ever going to get.

# Answer
> 3 votes
The better answer I can give you is to do this preliminary steps:

**1. Evaluate the offort required to build a prototype.**

Your prototype should be playable, limited in space (levels or map size or whatever space-related), in features (non customizable colors or static version of dynamic features). A pro if such a prototype may be evolved into a demo version easely.

**2. Evaluate the target.**

You have to do this before even try to start a such thing using one of the most valuable things you own: the time.

**3. Find a cheap/free pretest comunity.**

If you want to make a social game you have to reach a relative consistent number of people who are willing to try your game for free. How to obtain this may vary a lot, generally games are appealing things but your prototype may be less actractive as as it could be. If your target is young enough, you may think to add some educational aspect - even forcing it a bit - and try to propose it as project for a school: you can receive a lot of very valuable feedbacks.

To be honest, "volunteering" something good for children is itself something very rewarding and a good way to spend time. If you can reuse the codebase of an educational project - that you give for free - in a profitable project, you absolutely are on the right track.

---
Tags: ios, windows-phone-7, business, content-generation, user-generated-content
---


title: QT for lan game devleopment

text:
# Question
Title: QT for lan game devleopment
I am making a small game for a course in my school and was planning on using QT to build it. I have worked with pygame\[last year\] and turbo c++\[about 5 years agao\] to make games, small easy stuff. This time I am planning to make a game that supports multiplayer over lan, the game idea is simple however, information about the game is here.

I was hoping to know from you all, if it is a good choice to use QT for this! I am totally new to QT, but a decent c++ programmer. Also what problems would I encounter when it is a LAN game, for a start I just want it to support 2 players on the local network.

Thanks

# Answer
> 1 votes
Using QT is not a bad choice, more important is the networking. As you are developing for LAN you should be alright with TCP networking. In fact I'd even go so far as to recommend it to a first timer. Just be aware when you are working with TCP it will guarantee delivery, guarantee packets arrive in order, and provide a stateful connection for you. The problem with TCP is it doesn't work well over the Internet, the things it guarantees come at a price that increases with bad connections, which over the Internet it becomes too costly for some applications. Either way I would recommend the use of RakNet because it's open source you can learn a lot of useful tips for networking in general. Google for website URL. Good luck!

# Answer
> 1 votes
As it is over a LAN there shouldn'nt even be a discussion about UDP/TCP, go with TCP as it is much more easier to use.

Qt for a game or not?

That is a completely different history, go with it if you feel like it, it is a nice framework.

What you should check out is IP broadcasting (or scanning as routers usually just dismiss IP broadcasts) or if you can, Ethernet broadcast so you can find the other computers on the network fast and easily (you will want to know where the PC that hosts the game is).

Also read up on dead reckoning if you don't know that one or go with the 'ol 'lock step' method (simpler but that will be hell to use over the internet :-) to synchronize gamestates.

Anyway, do use the technology you feel most at ease with, that usually does the trick.

\[edit\] BTW: a must have for network programming is Beej's Guide to Network Programming simple, fun and precise.

---
Tags: multiplayer, qt
---


title: Does radiosity work with skylight?

text:
# Question
Title: Does radiosity work with skylight?
Does radiosity work with skylight (directional light)? From reading online it sounds like it was intended to work with point lights but I would really like to make it work with skylight if possible.

If I did misunderstand how would I make this work with skylight?

The form factor attenuates for distance, area, and orientation of the patches. It doesn't seem like that would all apply in skylight.

I have a primitive implementation of radiosity in the cpu using ray casting.

Any help is greatly appreciated.

# Answer
> 1 votes
Radiosity should work with any kind of light source; it's just a matter of how you define the first bounce.

After the original light sources have been considered, all the surfaces that have been hit by light rays become light sources for the second pass, and so on.

While I haven't implemented radiosity myself, I don't see why skylight/directional light wouldn't work on the first pass.

# Answer
> 1 votes
Actually skylight is one of the best applications. Point lights or spot lights are not the best fit for radiosity. Directional lights of area lights are just great for it (because they are not changing the complexity of render).

Also read something about atmospheric scattering and its approximations to have nice sky ;).

# Answer
> 0 votes
In radiosity, you don't usually have "point lights". Its based on radiant heat transfer between polygon faces (except we're talking about the visible spectrum of radiation instead of infrared). So every light source must be an area light source in radiosity.

You can have a really small point sphere of light.

---
Tags: lighting, radiosity, global-illumination
---


# Question
Title: Conversion of a number from Single precision floating point representation to a Half precision floating point
Hope it is relevant here.

I have a code where I have to work on Half precision floating point representation numbers. To achieve that I have created my own C++ class fp16 with all operators(arithmetic logical, relational) related to this type overloaded with my custom functions, while using a Single precision floating point number with a Half precision floating point number.

Half precision floating point = 1 Sign bit , 5 exponent bits , 10 significand bits = 16 bit

Single precision floating point = 1 Sign bit, 8 exponent bits, 23 significand bits = 32 bits

So what I do to convert from a Single precision floating point number to a Half precision floating point number:-

For significand bits - I use truncation i.e. loose 13 bits from the 32 bits to get 10 bits significand for half precision float.

What should I do to handle the exponent bits. How do I go from 8 exponent bits to 5 exponent bits?

Any good reading material would help.

# Answer
> 6 votes
Assuming a normal number (subnormal numbers are small enough so that they can be safely set to zero, infinities, zero, negative zero and NaN need to be handled specially anyway), you need to subtract the exponent bias from the exponent of the original floating point format (that's 127 for 32-bit `float`), and re-add the exponent bias of the new format (that's 15 for the 16-bit `half`) later.

* If the result is between 1 and 30, you can use it.
* If it's -9 to 0, you can try constructing a subnormal number. Alternatively, given the performance penalty associated with them on some platforms, you might not, and simply set the number to zero too, cutting off the value space in the result. Which of the choices is the better one depends mostly on your target hardware, but you should be aware that there *is* a choice.
* If it's 31 or more, you have an overflow and should construct an infinity or negative infinity, as applicable (those have the exponent set to 31 and the significant bits all set to zero).
* In all other cases (that is, if the resulting exponent would be -10 or smaller), the number is too small to be represented in a half-precision floating number. The result should be set to zero or negative zero.

In all cases: Beware of the exponent shifting up if you decide to round the significand instead of truncating it. Currently you are truncating it (rounding to zero), so that's not an issue.

# Answer
> 5 votes
Here are my two implementations. The first one uses branches, which can be a problem on an in-order CPU, but uses very little memory:

```
/* This method is faster than the OpenEXR implementation (very often
 * used, eg. in Ogre), with the additional benefit of rounding, inspired
 * by James Tursa’s half-precision code. */
static inline uint16_t float_to_half_branch(uint32_t x)
{
    uint16_t bits = (x >> 16) & 0x8000; /* Get the sign */
    uint16_t m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
    unsigned int e = (x >> 23) & 0xff; /* Using int is faster here */

    /* If zero, or denormal, or exponent underflows too much for a denormal
     * half, return signed zero. */
    if (e < 103)
        return bits;

    /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
    if (e > 142)
    {
        bits |= 0x7c00u;
        /* If exponent was 0xff and one mantissa bit was set, it means NaN,
         * not Inf, so make sure we set one mantissa bit too. */
        bits |= e == 255 && (x & 0x007fffffu);
        return bits;
    }

    /* If exponent underflows but not too much, return a denormal */
    if (e < 113)
    {
        m |= 0x0800u;
        /* Extra rounding may overflow and set mantissa to 0 and exponent
         * to 1, which is OK. */
        bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
        return bits;
    }

    bits |= ((e - 112) << 10) | (m >> 1);
    /* Extra rounding. An overflow will set mantissa to 0 and increment
     * the exponent, which is OK. */
    bits += m & 1;
    return bits;
}

```

The second one only uses tables, which uses some memory and thus can suffer from cache misses if used only from time to time:

```
/* These macros implement a finite iterator useful to build lookup
 * tables. For instance, S64(0) will call S1(x) for all values of x
 * between 0 and 63.
 * Due to the exponential behaviour of the calls, the stress on the
 * compiler may be important. */
#define S4(x)    S1((x)),   S1((x)+1),     S1((x)+2),     S1((x)+3)
#define S16(x)   S4((x)),   S4((x)+4),     S4((x)+8),     S4((x)+12)
#define S64(x)   S16((x)),  S16((x)+16),   S16((x)+32),   S16((x)+48)
#define S256(x)  S64((x)),  S64((x)+64),   S64((x)+128),  S64((x)+192)
#define S1024(x) S256((x)), S256((x)+256), S256((x)+512), S256((x)+768)

/* Lookup table-based algorithm from “Fast Half Float Conversions”
 * by Jeroen van der Zijp, November 2008. No rounding is performed,
 * and some NaN values may be incorrectly converted to Inf. */
static inline uint16_t float_to_half_nobranch(uint32_t x)
{
    static uint16_t const basetable[512] =
    {
#define S1(i) (((i) < 103) ? 0x0000 : \
               ((i) < 113) ? 0x0400 >> (113 - (i)) : \
               ((i) < 143) ? ((i) - 112) << 10 : 0x7c00)
        S256(0),
#undef S1
#define S1(i) (0x8000 | (((i) < 103) ? 0x0000 : \
                         ((i) < 113) ? 0x0400 >> (113 - (i)) : \
                         ((i) < 143) ? ((i) - 112) << 10 : 0x7c00))
        S256(0),
#undef S1
    };

    static uint8_t const shifttable[512] =
    {
#define S1(i) (((i) < 103) ? 24 : \
               ((i) < 113) ? 126 - (i) : \
               ((i) < 143 || (i) == 255) ? 13 : 24)
        S256(0), S256(0),
#undef S1
    };

    uint16_t bits = basetable[(x >> 23) & 0x1ff];
    bits |= (x & 0x007fffff) >> shifttable[(x >> 23) & 0x1ff];
    return bits;
}

```

# Answer
> 4 votes
Few years ago I have been solving the same problem - I wanted to use Half Float extension in OpenGL, so I needed to convert Float32 to Float16. I have found somewhere this code, so I hope it will help you too:

```
#define F16_EXPONENT_BITS 0x1F
#define F16_EXPONENT_SHIFT 10
#define F16_EXPONENT_BIAS 15
#define F16_MANTISSA_BITS 0x3ff
#define F16_MANTISSA_SHIFT (23 - F16_EXPONENT_SHIFT)
#define F16_MAX_EXPONENT (F16_EXPONENT_BITS << F16_EXPONENT_SHIFT)

GLushort F32toF16(GLfloat val)
{
    GLuint f32 = (*(GLuint *) &val);
    GLushort f16 = 0;
    /* Decode IEEE 754 little-endian 32-bit floating-point value */
    int sign = (f32 >> 16) & 0x8000;
    /* Map exponent to the range [-127,128] */
    int exponent = ((f32 >> 23) & 0xff) - 127;
    int mantissa = f32 & 0x007fffff;
    if (exponent == 128)
    { /* Infinity or NaN */
        f16 = sign | F16_MAX_EXPONENT;
        if (mantissa) f16 |= (mantissa & F16_MANTISSA_BITS);

    }
    else if (exponent > 15)
    { /* Overflow - flush to Infinity */
        f16 = sign | F16_MAX_EXPONENT;
    }
    else if (exponent > -15)
    { /* Representable value */
        exponent += F16_EXPONENT_BIAS;
        mantissa >>= F16_MANTISSA_SHIFT;
        f16 = sign | exponent << F16_EXPONENT_SHIFT | mantissa;
    }
    else
    {
        f16 = sign;
    }
    return f16;
}

```

# Answer
> 1 votes
I'll throw another reference implementation into the running:

https://github.com/HeliumProject/Helium/blob/master/Math/Float16.h

https://github.com/HeliumProject/Helium/blob/master/Math/Float16.cpp

---
Tags: floating-point
---