title: Is it possible to fake blur via images?

text:
# Question
Title: Is it possible to fake blur via images?
I'm using libGDX for an android game; as far as I can tell, it doesn't have an API for blurring.

Reading on Wikipedia, it seems like blur is formed by setting each pixels RGB values to the average of all adjacent values. Which doesn't seem easily possible in libGDX -- setting pixel data.

So my question is simple:

**Is it possible to fake (a decent) blur using only images?**

I can potentially overlay multiple (in number, transparency, type) images; but can I create a convincing blur like this?

I'm tempted to say "no," but maybe someone else has achieved something similar. For clarity, I want a set of 1+ generic images I can render on top of ANY image to generate a blur-like effect.

# Answer
If you're able to additively blend images and multiply them by a constant while doing so, then you can do a blur. Instead of averaging the pixels in a neighborhood, you'd average several copies of the image displaced by a small number of pixels from each other. Or more generally, you could do a Gaussian blur or whatever kind of blur, by controlling the weights - that is, multiplying each displaced copy of the image by a constant as it's being added onto the rest.

Algorithmically, it would look something like this:

```
clear output_image to 0
foreach offset, weight in filter_kernel:
    output_image += input_image * weight, shifted by offset

```

You'd use the same offsets and weights as in the standard way of doing a blur. There are plenty of articles on the Web on how to generate the weights for a Gaussian blur, for instance.
> 7 votes

# Answer
Blurring can be an expensive operation, perhaps a different approach could work, e.g.:

1. Store multiple copies of the image blurred in several different directions (e.g. multiples of 45 degrees), then display the closest matching image at runtime. This will offer the highest performance, at the cost of memory usage.
2. Scale the image down and then back to full-size with anti-aliasing/smoothing. Often this can be done with graphics hardware with very little performance impact.
> 0 votes

---
Tags: graphic-effects
---


# Question
Title: How can I implement "cut outs" for lighting in OpenGL?
So, I'm working with OpenGL (I'm not exactly sure of the version), and I want to do an old-style lighting setup by essentially drawing a black rectangle over the screen, and drawing white circles over the areas that should be lit. I already have the rectangle and the circles, but I can't figure out how to make it so that the white circles are transparent when applied to the black areas. Any ideas? I tried to use blending modes, but it still evades me...

EDIT: Here's the code that I'm using (Python).

```
view_buf = Buffer(GL_INT, 4)
glGetIntegerv(GL_VIEWPORT, view_buf)
view = view_buf.to_list() if hasattr(view_buf, "to_list") else view_buf.list

glDisable(GL_DEPTH_TEST)

glDisable(GL_LIGHTING)

glEnable(GL_BLEND)

if logic.lights['smooth']:
    glEnable(GL_LINE_SMOOTH)

# # Make sure we're using smooth shading instead of flat
# glShadeModel(GL_SMOOTH)

# Setup the matrices

glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
gluOrtho2D(0, view[2], 0, view[3])
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()

#glAlphaFunc(GL_GREATER, 0.5)

glColor4f(0.0, 0, 0, 0.75)

glBegin(GL_QUADS);                              # Draw Black screen
glVertex2d(0.0, 0.0);
glVertex2d(view[2], 0.0);
glVertex2d(view[2], view[3]);
glVertex2d(0.0, view[3]);
glEnd()

glColor4f(1, 1, 1, 1)

degtorad = 3.14159/180.0

glBlendFunc(GL_ZERO, GL_SRC_ALPHA)

def DrawCircle(x, y, radius, fill = 1, step = 11):

    glVertex2f(x, y)

    if fill:
        glBegin(GL_TRIANGLE_FAN)
    else:
        glBegin(GL_LINE_LOOP)

    for a in range(0, 360, step):
        angle = degtorad * a
        glVertex2f(x + (sin(angle) * radius), y + (cos(angle) * radius))

    glEnd()

#for layer in range(len(logic.lights['layers'])):
#   size =
for light in logic.lights['points']:
    DrawCircle(light[0][0] * view[2], (1 - light[0][1]) * view[3], light[1], step = light[2])
    if logic.lights['smooth']:
        DrawCircle(light[0][0] * view[2], (1 - light[0][1]) * view[3], light[1], 0, light[2])

# Reset the state
glPopMatrix()
glMatrixMode(GL_PROJECTION)
glPopMatrix()

```

# Answer
You can use the stencil buffer using a technique similar to the one described here for rendering to a non-rectangular viewport (as that is essentially what you are doing).

When you clear you scene, clear the stencil buffer to some fixed value (say zero). When you render the lit areas, configure the stencil mask to write a different value (say one) to the buffer. Then render your regular scene with the stencil function configured to accept only fragments where the stencil value is greater than 0.

This will cause only fragments within the lit areas to render. It's straightforward, but it has the (fairly severe) disadvantage of providing very hard edges to the lit regions.

The other options are to perform the entire effect in the pixel shader using a shader global for the position and radius of the light source (problematic for supporting more than one light source) or alpha blending precomputed textures into the scene (this is the most general method, easily supporting multiple light sources and smooth transitions into darkness).
> 0 votes

---
Tags: opengl, 2d, lighting, blending
---


# Question
Title: How can I create a "night sky" effect in OpenGL?
I am creating a game using OpenGL and I want to render the effect of a night sky with a few stars in it.

I want to have a shiny black effect in the sky so that it looks good. Could some one help in how to proceed through it or give a link to a good tutorial?

# Answer
> 11 votes
Typical approaches are skyboxes or skydomes. Both techniques involve creating some simple geometry that is always rendered in a fixed position relative to the view, and applying a texture to it. The quality of the resulting effect can depend heavily on the quality of the texture artwork, so if you don't have great art skills you may want to opt for something else. Tools like Terragen can help produce decent art though, and this question has a set of links to other tools of a similar nature.

A less obviously art-dependent approach is to do the whole thing procedurally. You can create a vertex-color based skydome (links and information here) which will allow you to adjust the colors according to some empirical (or other) models for sky coloring -- Preetham and Shirley's model is particular nice, if I recall correctly.

You can then apply procedural starfield generation which you render near the sky dome (perhaps as a fixed particle system, or via texture splatting, or whatever).

---
Tags: opengl, sky
---


# Question
Title: How can I render a shiny, metallic surface?
I am creating a game for which I want to render a kind of shiny black metallic surface with some refection property in it. I know that there would be something related to masks involved with it. But somehow I am not able to get started on it.

So could someone give me insight in the matter or give a link to a good tutorial?

# Answer
> 8 votes
Reflection can actually be fairly tricky because you need information about the surrounding scene before you can render a reflective object. The more accurate you want the reflection to be, the harder it is to implement.

For example, if you just want to reflect the surrounding environment (skybox) you can use environment mapping. Spherical or cube mapping are common (the latter is probably the most common as the cube textures required are much easier to produce; any tool that creates a sky box can be used). These techniques are simple, fast, and can be used on arbitrary geometry. However they will not provide local reflections (that is, reflection of other objects in the scene).

Planar reflective surfaces are another option. These can be done in a variety of fashions -- simply flipping geometry, rendering to a texture and flipping that, stencil buffer techniques, et cetera. This technique is often used to render water, but metallic surfaces can be done just as easily -- in fact easier, since you generally won't bother with the distortion effects also involved in creating water. This technique is also relatively fast, but only works on planar surfaces, as the name implies.

A third option is dynamic cube mapping. This is akin to a combination of parts of both previous techniques -- using a cubic environment map, so arbitrary geometry can be used as the reflective surface, but updating that cube map every frame with the contents of the rest of the scene. Obviously doing so is more expensive. You can find some discussion on this technique here, and a demo here.

Obviously, plugging any of these terms into Google will yield a plethora of results as well, which you should check out for more information.

---
Tags: opengl, rendering
---


# Question
Title: Polishing your game: how much is enough?
I'm assuming you're an indie developer, doing your own (or getting free/partner-based) artwork. I'm also assuming you have no external pressure driving you forward into new games; you can work on your games as much (or as little) as you want, then move on.

Having said all that, **how do you decide how much polish to put in a game?**

I'm also assuming you won't fall into the notorious trap of dumping your game half (or less) finished; that you have the discpline to work on it until it's "good (enough)."

I currently have a rough cycle where I develop the core functionality, then content/levels/whatever, then add layers of polish (art, bug-fixes, and usability tweaks) until I get bored. There's always scope to improve, but I don't have a measuring stick telling me that "at this point, your return on polishing is not worth the time/effort you're putting into it."

I'm going to assume this is **always worth it** if you learn something new (like how to render a glow effect, say).

Also, before you ask, I don't have much of a player base (and not one I can observe, either) to ask *them* when it's good enough.

# Answer
> 32 votes
> I'm going to assume this is always worth it if you learn something new (like how to render a glow effect, say).

That's a poor assumption. Indeed, I would even say that this assumption suggests that your general idea of "polish" isn't necessarily polishing anything important.

"Polish" is not adding glow. "Polish" would be adding glow to something such that it makes the game better in some material way. Does that object need to glow? How does that glowing fit into your overall visual design aesthetic? Do other objects need to glow in order to make the entire presentation more coherent?

Gratuitous effects are gratuitous. As are gratuitous AIs, gratuitous levels, gratuitous enemies, gratuitous areas, etc.

In a well-designed and well-polished game, every element exists for a purpose. Putting more "stuff" in a game does not make it more polished. Making the game a coherent, cohesive work is what makes it more polished.

This will generally involve doing boring stuff. Making a UI that looks like it belongs in that kind of game. Making sure that all your UI elements have a consistent look and feel. Making sure that your UI screens all make sense and have consistency and logic to them. Ensuring that enemies and other objects of interest are visible and noticeable, popping out of the background. Ensuring that the player's play experience through the game is smooth; the game doesn't get too difficult too early, and it doesn't get too easy later on.

Polish is all of those little things that you know you need to do, but take a long time and in many cases aren't very interesting. And they're certainly not why you started making the game in the first place.

Yet these are what makes a good idea into a great game. And these things are not easy to do. They require a lot of grunt work.

The only real way to know how much is enough is to give the game to other people and let them play it, then see how they react. Ask them if there is anything that feels missing from the experience, or if they ran into trouble, or anything of that nature.

# Answer
> 9 votes
> Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.

For non-indie games, how much polish is usually a matter of time and money. You have a budget, release window, and so on, and you usually just find the highest priority things (hopefully from the user's perspective, but sometimes from the other internal forces like IP holders and the like) to do first. Eventually you have to cut your losses and ship.

But for you, I would probably frame the question a different way. Assuming you haven't released yet, the amount of polish is more an effect of when you're proud enough of the product to put it in front of people.

> at this point, your return on polishing is not worth the time/effort you're putting into it.

The only person who can determine the return is you. Are you learning something new? Are your skills improving? Are you looking at it from a "how many more units will this potentially get me" perspective? Would you get a better ROI by starting a new project? There isn't an easy way to answer that question in the general case.

---
Tags: process
---


# Question
Title: How do texture lookups for trig functions work?
I have a pixel shader that calculates a mandelbrot fractal. It uses the standard formula:

z = z2 \+ c

I'd like to extend it so the power z is raised by varies. To do this i have the following function:

```
float2 ComPow(float2 Arg, float Power)
{
    float Mod = pow(Arg.x * Arg.x + Arg.y * Arg.y, Power / 2);
    float Ang = atan2(Arg.y, Arg.x) * Power;

    return float2(Mod * cos(Ang), Mod * sin(Ang));
}

```

The problem i've got is the xbox does this really slowly compared to squaring a complex number. I'm thinking it's partly because of the increased number of instructions, but mainly it's using trig functions (cos, sin and atan2).

I tested this by adding a single atan2 within the for loop and it's visibly jerky, whereas before it was getting a good FPS.

Can i use texture lookup to speed up / replace the `cos`, `sin` and `atan2` calls? If so, how?

# Answer
> 4 votes
Maybe. The problem you'll likely run into with replacing math functions with a texture lookup is precision and range. The texture can only be so large, and you have to decide what region of the function's domain it's going to cover and how finely subdivided in the domain it needs to be. Then, with standard texture formats you have only 8 bits to encode the output value, so again you need to decide what range of outputs you're going to support and how precise the output needs to be. You can use floating-point textures as well, but then they will be slower to read, and I think you also do not get bilinear filtering on floating-point textures on the X360.

It also may or may not be faster than just evaluating the math functions directly. Texture lookups are vastly more expensive than ALU (math) operations on a GPU, because of the high latency of memory access.

All that said, if you want to give it a shot, you'll basically need to allocate a texture of the size you picked, and write some init code to populate it by looping over all the pixels and evaluating the function at the domain point corresponding to each pixel. Then bind it like any other texture in your shader, and replace your math function with a tex2D call (with appropriate scale-biasing to convert the domain point to a UV point). I'm not familiar enough with XNA to tell you the exact calls you'll need, but it shouldn't be too hard to figure out.

---
Tags: xna, optimization, fragment-shader, fractal
---


# Question
Title: How do I implement anti-aliasing in OpenGL?
I want to do full-screen anti-aliasing in OpenGL, and dont want to use the anti-aliasing that is provided by OpenGL itself, since I am building a game and want good effects in it.

How should I proceed?

# Answer
> 37 votes
There are several alternatives to native MSAA in OpenGL. With post-processing effects, the best thing about them is that you can usually just throw in the shader to the final, unprocessed image and it does the rest. Here are three methods worth taking a look:

* Fast Approximate Anti-Aliasing (Geeks3D) \- Good in most cases. Pretty easy to apply and understand. Drawback is sharp, high contrast noise in textures gets blurred a bit. Edges as subtle as 1/4 pixels steep look dead-accurate as traditional MSAA. Any less steep than that, it loses a bit of accuracy.
* Normal Filtered Anti-Aliasing (GameDev) - Haven't tested this one yet accurately, but it's the easiest to understand. In best cases it resembles 16x MSAA and in worst cases it's like 2x MSAA. It generates a temporary normal map to represent edges and relative angles. You can sample the normal map either with luma difference or color difference.
* Morphological Anti-Aliasing (Iryoku) \- been improved to SMAA - Subpixel Mophological AA. It's pretty complex at 4 passes, but achieves the best results I've seen. It creates gradients along edges as gradual as 1/100 to 1/200 pixels steep (!). Sampling can be luma-based, color-based or depth-based. Textures stay very crisp and clean. (the example is DX10 and HLSL based, would take some time to port it to GLSL accurately)

These techniques don't super-sample or multi-sample, so lines that appear less than 1 pixel in thickness will appear with gaps and not be anti-aliased correctly. This is the downside to using a non-MSAA approach. Since you're only working with a raster image at full resolution, you can't create additional information from these empty gaps.

Take notice that all of these techniques are dependent on sampling adjacent luma (brightness) or chroma (color) values. Calculating luma and optional gamma correction requires additional instructions on the AA shader, though it's pretty straightforward. You can offload this by calculating the luma in the previous shader that provides the un-retouched image, storing the luma in the alpha channel. Then in the AA shader, you will simply sample the alpha.

# Answer
> 9 votes
There's lots of ways to do antialiasing. One is to use multisample antialiasing (MSAA), where your back buffer actually stores multiple sub-pixel samples, and when you render triangles, lines, etc. the system automatically fills in the correct set of samples in each pixel. Then at the end of rendering the image is "resolved" by averaging over all the sub-pixel samples to get one sample per pixel.

Another way is to use post-processing antialiasing, where you render the scene as normal and then do some targeted blurring on the end result to hide aliased edges. There are a variety of techniques for this, but one of the best / most popular at the moment is called FXAA (Fast approXimate Anti-Aliasing).

MSAA will generally give better-looking results than post-processing AA, but can be slower because it requires approximately double the memory bandwidth for every rendering operation. MSAA can also require more video memory than post-processing AA, depending on the details of the setup.

You can find specific info about implementing either MSAA or FXAA on the Web - just google either one of those terms.

---
Tags: opengl, antialiasing
---


# Question
Title: How does one avoid the "staircase effect" in pixel art motion?
I am rendering sprites at exact pixel coordinates to avoid the blurring effect caused by antialiasing (the sprites are pixel-art and would look awful if filtered). However, since the movement of the objects involves variable velocity, gravity, and physical interactions, the trajectory is computed with subpixel precision.

At large enough screenspace velocities (vΔt larger than 2 or 3 pixels) this works very well. However, when velocity is small, a noticeable staircase effect can appear, especially along diagonal lines. This is no longer a problem at very slow screenspace velocities (v \<\< 1 pixel per second) so I am only looking for a solution for intermediate velocity values.

On the left is the plotted trajectory for a large velocity, obtained by simple rounding of the object coordinates. In the middle you can see what happens when velocity becomes smaller, and the staircase effect I am talking about. On the right, the locus of the trajectory I would like to get.

I am interested in algorithm ideas to filter the trajectory in order to minimise the aliasing, while retaining the original behaviour at large and small velocities. I have access to Δt, instant position and velocity, as well as an arbitrary number of previous values, but since it is a realtime simulation, I do not know about future values (though if necessary, an estimation could be extrapolated under certain assumptions). Note that because of the physics simulation, sudden direction changes can also happen.

# Answer
> 19 votes
Here's a quick outline, off the top of my head, of an algorithm that ought to work reasonably well.

1. First, calculate the direction the object is moving, and check whether it's closer to horizontal or vertical.
2. If the direction is closer to vertical (horizontal), adjust the position of the object *along the direction vector* to the center of the nearest pixel row (column).
3. Round the position to the center of the nearest pixel.

In pseudocode:

```
if ( abs(velocity.x) > abs(velocity.y) ) {
    x = round(position.x);
    y = round(position.y + (x - position.x) * velocity.y / velocity.x);
} else {
    y = round(position.y);
    x = round(position.x + (y - position.y) * velocity.x / velocity.y);
}

```

Edit: Yep, tested, works quite nicely.

# Answer
> 4 votes
When the pending movement is perpendicular to the last movement (in screen space), ignore it and use the last screen coordinates. If that lead to stutter that's as bad as the staircase, you might try moving the sum of the pending and last movement.

I think the problem lies in v \< sqrt(2). v \> sqrt(2) should always move at least a full diagonal, avoiding the staircase effect. Maybe useful for pruning which need the prior movement comparisons.

# Answer
> 3 votes
There's not much you can really do about that for a general physics-based world. If all of your objects were moving along lines or specific circles, you could do something. But you're operating under actual physics. The object is where the physics puts it; you are simply drawing a pixel-based approximation of that location.

It's generally something you have to accept if you want to stick with pixel coordinates. It shouldn't be too noticeable unless you're displaying at an incredibly small resolution (less than 640x480, though it depends on the display's native resolution and size).

---
Tags: physics, interpolation, trajectory, pixel
---


# Question
Title: Is it possible to build an app with Corona with only a PC, and expect it to reasonably run well on an iPhone?
So I understand that Corona allows me to "write once," and deploy on both iPhone and Android. And I understand that I cannot get any iPhone app into the app store without having (at the moment of submission/distribution) an (Intel-based?) mac (physical hardware).

I assume that if I only own PC hardware, I will not be able to test-deploy my game to an iPhone, nor see how the performance might be on an iPhone; but given those limitations, can I expect my Corona app to work decently if it performs decently on the Windows SDK and iPhone versions?

# Answer
> 5 votes
**No**. The device has an entirely different hardware than your PC and testing your App solely on the Simulator isn't going to be enough. You might hit problems in the simulator that won't occur on the device and vice versa. The simulator also doesn't simulate memory constraints of a device.

I know that getting a Mac and an iPhone can be rather expensive, but I'd look around for used hardware. A Mac mini can be a good choice as these are rather cheap and won't take up much space. A cheaper alternative to the iPhone is the iPod. The hardware is essentially identical (apart from the actual "phone").

If you own an android device with similar specs to the iPhone, you might use that for testing during development and ask a friend that owns Mac hardware to test the game at key-points in development. Still, there's no way around testing on the actual device.

---
Tags: android, iphone, corona-sdk
---


# Question
Title: Optimal data size for a 3G client-server game?
I'm currently working on an iOS turn-based client-server game and I am concerned over later performance issues.

How much data per message is too big? I am planning to use JSON to transfer data (and, if possible, gzip it for more compression) and try to send as little as possible to make it work, but is there a figure I should keep in mind so that I do not exceed and is there a best-practice way of compressing this data?

On a side note, will this prevent me or affect whether I will use secure connections like SSL?

# Answer
> 11 votes
You will probably need to micro-manage the 3G modem to ensure that you don't have delays while it switches power modes. Your simple answer is make sure you send at least one packet larger than 128 bytes every 6-8 seconds. If you can guarantee that all your packets are smaller than 128 bytes make sure you send something once every 6-8 seconds. Avoid, at all costs, switching between 3G power states in a game as you will be cut off for 2.5 seconds while the transition occurs.

# My Packets Are All Smaller Than 128 Bytes

Have a timer kick off every 6 seconds or so. If no packet has been sent since the last timer event, send a small heartbeat packet (4 bytes is probably safe).

If you sometimes need to send large data you could queue it up for temporary jumps to DCH.

Turn OFF Nagling if you are using TCP.

# My Packets Could be Larger Than 128 Bytes

Have a timer kick off every 6 seconds or so. If no packet has been sent since the last timer event, that is at least 128 bytes; send a large heartbeat packet (196 bytes is probably safe).

Turn ON Nagling - if acceptable (i.e. your game is not real-time).

# 2.5s Delay is Acceptable

*This is probably your case.*

Do nothing special. Just make sure that your UI is ready for something like this (i.e. ensure it supports background workers/async).

# More Info

Taken from the rather good XMPP mobile recommendations. Keep in mind these are not set in stone, and are up to the network operator - you can get feedback about this from the phone on some platforms:

## Idle

*connections but no data, ~8mA*

This mode is used when connections are not actively sending/receiving data.

## FACH

*\<= 128 bytes per packet, ~140mA*

This mode is used when the packet queue remains smaller than 128 bytes for 8s. It takes 2.5s for your cellphone to move from idle to FACH.

## DCH

*\> 128 bytes per packet, ~380mA*

This mode is used when one or more connections are sending packets larger than 128 bytes at least once every 8 seconds. It takes 2.5s for your cellphone to move from FACH to DCH.

# Answer
> 1 votes
Basically, it depends. Don't worry about it until you have a bottle neck. However you probably won't hit any issues on a 3g connection for a turn based game.

# Answer
> 0 votes
I would advise against sending it in json as it is in plain text. your computer reads and understands binary, your server reads and understands binary, so why not just put the data into the pakcets in this format. sending any other way has unnecessary overhead, compression / decompression and overhead in parsing, when you could just stream your objects into and out of the packets

---
Tags: networking, mobile, client-server, turn-based
---


# Question
Title: What technologies are required for 3D game development?
I want to make a racing game like Need for speed. And I want to start from very start. Please tell me the skills, technologies that one should posses while making it.

I am beginner in game development, Although I have good programming skills. I am ready to learn. Please also recommend few good books.

Thanks in advance.

Updated: I am interested in making PC games and I have no intention in making my career in gaming. Also no 2D games, just full-fledged 3D games. Here I don't think like creating a games like pacman or mario are gonna help me. if they, then please pardon me.

Updated: Why should I learn 2D game development? I want to develop a 3D game.

# Answer
> 1 votes
The recent Need for Speed series were developed by teams of several dozen professionals working full time for several years with the accumulated experience of their previous projects. I believe the major skill to possess when trying to develop a game is project management: when you know and accept that you are talking about a 20 to 200 man-year project, you'll be ready to start.

For 3D graphics programming I would recommend Real-Time Rendering, The OpenGL Programming Guide and The OpenGL Shading Language. I think the first one is a must have, even for graphic artists who need to understand the modern GPU pipeline.

Knowledge of C++ is probably necessary if you want both performance and portability. But if you really want to write everything from scratch, Python and OpenGL could be a reasonable solution at least for prototyping. And if you are using a game engine such as Unity or UDK, you may not even need to program at all.

You will need to know about 3D modelling, maybe rigging and animation for your cars, characters and other game assets. You will need to know about maths and physics for your driving simulation to be accurate, for your lighting to be realistic.

# Answer
> 7 votes
> And I want to start from very start. Please tell me the skills, technologies that one should posses while making it.

Start from the very start, eh? Well, first you're going to need to know math. A lot of math. Algebra, Trigonometry, Matrix Rotations, and a whole lot of physics if you want to do everything from scratch. This should take about 1-2 years if you study hard, depending on how much you already know.

Second, programming, and lots of it. The good news, you can learn math while learning programming, since there's a decent amount of cross over. Outside of simple everyday stuff of programming, which you claim to have good knowledge of, you'll need to learn about stuff like game loops, rendering pipelines, model importing and exporting, user input, graphics output, probably some low level file handling stuff if you want people to be able to save their games, AI (which can include scripting, behavior trees, finite state machines, and all sorts of other buzzwords), GUI programming, event systems, camera controls, collision detection, and a lot of other things specific to 3d programming (mostly having to deal with the tricky parts of rendering a 3d model and handling animation and other stuff). This can take 5-10 years, depending on skill level ad other factors.

Third, art. Now that you've learned math and programming (you should reach this point somewhere around 2018), you've got a 3d racing game that uses simple colored boxes for the graphics. And grey flat planes for the roads. So, now you can spend the next 5-10 years learning about color theory, material theory, 3d modeling programs, animation/rigging, texturing (how to make the 2d art that gets put onto models), various forms of mapping (bump map, light maps, UV maps), and a *whole lot* of other bits of art that I don't really know about.

By the time you're done with this, sometime around 2025, you should have a game that is comparable to a current Need for Speed game. This time frame also assumes you are *wildly* talented in everything and you only focus on increasing your skills and not much else.

*P.S. I'm sorry for being harsh, but as people have said, the Need for Speed games are made by large teams of about 100+ people who have years of experience in **their** discipline, even a small 3d indie game can take 5-10 people a few years to make. Using Unity and UDK might speed things up a bit, but it's still going to take years. To quote some parkour guy: **"There are no shortcuts in becoming good"** This is why everyone says to make some 2d games first, it'll help you understand **what** goes into making a game. Because a lot goes into making a game.*

# Answer
> 4 votes
> I am beginner in game development, Although I have good programming skills. I am ready to learn. Please also recommend few good books.

Programming skills in what? jQuery isn't going to help, you need experience in C-like languages and extensive knowledge of 3d graphics and physics. Very few individuals can learn every aspect of these things needed for a game like Need for Speed, which is why professional teams make these sort of games.

In other words, doing this from scratch would be near-impossible and would take years.

You have 2 viable options:

1. Use an engine like Unity. It will provide you with 90% of the code you need. I believe Unity uses C#.
2. Modify a pre-existing game. Most will be under GPL so you'll have to release under it too. Will likely use C++ or C.

# Answer
> 4 votes
I start by telling you that I'm not a 3D game programming guru, in fact I'm hacking my way through the world of 3D game programming. (Coming from a background of desktop programming and WEB programming). So, take my advices with a grain of salt.

I already assume that you know C/C++ and basic things like OOP, STL, design patterns, data structures and algorithms.

I would start like this:

1. Learn a 3D api: either OpenGL, either DirectX. Don not make the mistake to learn the fixed-function rendering pipeline. It may be easier for starters but not only is dated, is way less performant than programmable pipeline. So look for books/tutorials which teach you programmable rendering pipeline.
2. Basic math: vector and matrix algebra is a must. Some basic trigonometry and analytic geometry may prove useful.
3. Start learning about algorithms and techniques used in 3D games for: scene management, shading, lightning, skeletal animation, texture mapping, texture filtering and blending and lots of others.
4. Learn how to use a physics engine, there are many good engines out there: PhysX, Havok, Bullet. Can be used for collision detection, too.
5. Learn AI for game programming.
6. Input, sound, network.

I wouldn't start directly with a game as complex as NFS. Even the 3D programming gurus started with simple things. Folks who were shooting to high in programming got stuck very fast. Many of those gave up. A few realized that they were shooting too high and started with the basics. Now they are doing advanced stuff.

So consider picking some good books and tutorials and start with examples from those books and tutorials. Start with simple stuff like rotating cubes, texture mapping, 3d model loading. Try making simple 3D games like a 3D platformer, a 3D Breakout, a 3D Tetris, a 3D Bomberman and the likes. Move to a simple 3D FPS, etc.

After you'll have a game engine, you have to start worrying about tools - you'll have to write at least a level design tool -, level designing and 3d modelling. As a indie developer you can find some free or cheap 3D models online. If you want more, a collaboration with 3D artists might be a good idea.

Some books I know are good and useful. Keep in mind that this list is far from exhaustive and there are other good books on 3D and game programming (some possible better).

OpenGL:

OpenGL SuperBible: Comprehensive Tutorial and Reference (5th Edition)

OpenGL® ES 2.0 Programming Guide

Beginning OpenGL Game Programming, Second Edition

Interactive Computer Graphics: A Top-Down Approach with Shader-Based OpenGL (6th Edition)

OpenGL Shading Language (3rd Edition)

Graphics Shaders: Theory and Practice

DirectX:

Beginning Game Programming

Introduction to 3D Game Programming with DirectX 10

Advanced 3D Game Programming with DirectX 10.0

Introduction to 3D Game Programming with Direct X 9.0c: A Shader Approach

Game Coding Complete, Third Edition

Other:

Game Engine Architecture

ShaderX7: Advanced Rendering Techniques

GPU Pro: Advanced Rendering Techniques

GPU Gems 3

GPU Computing Gems Emerald Edition

Real-Time Rendering, Third Edition

Game Programming Gems 8

Game Coding Complete, Third Edition

# Answer
> 3 votes
Consider learning XNA(.NET, C#) as a start. It is quite newbie-friendly and there are lots of samples and tutorials:

http://create.msdn.com/en-us/education/gamedevelopment

It lets you develop for PC, Xbox360 and Windows Phone. Using Mono and some commercial tools (MonoTouch + MonoGame) you can even enable porting to Mac, iPhone and Android.

Furthermore there is an actual sample of 3D NFS-like game:

http://create.msdn.com/en-US/education/catalog/sample/racing\_game

It is archived now as it was built for previous version of the framework - 3.0, but upgrading should not be too difficult.

> Also no 2D games, just full-fledged 3D games. Here I don't think like creating a games like pacman or mario are gonna help me. if they, then please pardon me.

It will help you. It is a common time-proven advice:

What are good games to "earn your wings" with?

> Why should I learn 2D game development? I want to develop a 3D game.

Because it might simplify things for you. Also a well-designed game code should make it easy to switch.

# Answer
> 0 votes
If javascript is what you're comfortable with, you should look into WebGL. Download chrome and try out the tutorials.

It's easier to get started with WebGL than with native code (you don't have to write all the OS specific windowing code) and most of the skills will transfer to other platforms, including Windows and iOS.

Based on the advice in this thread, with your interests I would start with something simple like Pole Position. If you do it well (and submit it to places like the one I linked to above) you might actually get some people to play it.

---
Tags: 3d, books
---


# Question
Title: How can I rotate a sphere in response to mouse movement?
I'm using jMonkeyEngine to develop a game. I'm good at scripting, but math *usually* goes over my head. I tried the Wiki page for Quaternion, but I was far too confused to figure this out myself :P

## My goal

I have a sphere with physics enabled, and I want to have it rotate based on mouse axis movement. I've got listeners set up properly so that in this method:

```
void roll(int axis, float tpf) {
    Quaternion rot = this.getPhysicsRotation();
    switch(axis) {
        case MouseInput.AXIS_X:
            // Rotate here
            break;
        case MouseInput.AXIS_Y:
            // Rotate here
            break;
    }
}

```

an axis and a value (+/-) will be provided. Once I figure out how to modify Quaternions, I'll just use `RigidBodyControl.setPhysicsRotation(Quaternion)` to update the rotation.

## My Problem

I'm clueless about Quaternions.. I don't even know what method I'd be using. I assume `Quaternion.add()` or `.mult()` will be necessary.

Someone please help! Here's a link to jme's Quaternion class for reference.

## Solution

From Zoltan's answer:

```
void roll(int axis, float tpf) {
    tpf *= 10;
    System.out.println("roll("+axis+","+tpf+")");
    switch(axis) {
        case MouseInput.AXIS_Y:
            Quaternion quaternion = new Quaternion();
            this.setPhysicsRotation(getPhysicsRotation().mult(quaternion.fromAngleAxis(tpf, Vector3f.UNIT_X)));
            break;
        case MouseInput.AXIS_X:
            Quaternion q = new Quaternion();
            this.setPhysicsRotation(getPhysicsRotation().mult(q.fromAngleAxis(tpf, Vector3f.UNIT_Y)));
            break;
    }
}

```

I'm not quite sure why `case:MouseInput` had to be swapped, but it works this way so.. *shrug*

# Answer
You don't really need to know stuff about quaternions for this. Consider the following:

```
Vector3f xAxis = sphere.worldToLocal(Vector3f.UNIT_X, null);
Quaternion quaternion = new Quaternion();
sphere.rotate(quaternion.fromAngleAxis(yRot, yAxis));

```

This will rotate your sphere about the x-axis for the given angle. You need to use worldToLocal because as you rotate your sphere around arbitrary axes, its local axes get rotated too.

As for why the y and x axis needed to be "swapped", you're not swapping anything, just think about it. When you're moving your mouse along the y-axis, you're rotating your sphere about the x-axis and vice versa. This is exactly what your code is saying.
> 2 votes

# Answer
Have you considered an arcball implementation? They are relatively straightforward and produce reasonably intuitive means of manipulating objects in 3D space. Essentially, you project the mouse coordinates from the current and previous frame onto an imaginary sphere that surrounds your object (in this case, it is a sphere, so there's that) and then compute the shortest arc quaternion between the two points.

You can then convert that quaternion to a matrix to apply it. Do note that APIs choose slightly different conventions for quaternion representations and your math may need to be adjusted to account for that (I don't know what convention jMonkeyEngine employs).
> 0 votes

---
Tags: mathematics, rotation, quaternion, jmonkeyengine
---


title: Which game platform has the most users?

text:
# Question
Title: Which game platform has the most users?
If I make a game, what is the best target platform for the most users?

If I don't have an iphone/ipad or android phone, am I not able to make iphone/android game?

I am looking for a platform which I can easily distribute the game for public trial/demo.

# Answer
> Game platform which have most users

That would probably be Web in general.

> If I don't have an iphone/ipad or android phone, am I not able to make iphone/android game?

Consider using HTML5. That would simplify deployment. However you might still want to have a device(s) to test.

> I am looking for a platform which I can easily distribute the game for public trial/demo.

HTML5 based game would fit this requirement.
> 9 votes

# Answer
Those are a couple different questions you're asking here.

The single target platform with the *most* users is the PC. Even counting just gamers, the biggest MMO *alone* (Happy Farm) had more than 200 million players at its peak. Compare that to some 70 million sold iPhones (all models, as of end of 2010), 190 million sold Android devices (as of end of October 2011), XBox 360 (55 million units sold), Wii (almost 90 million units sold) or PS3 (50 million units sold) - and only a portion of iPhones and Android devices are used for gaming.

The platform which is the best for *you* to get the most users depends heavily on what style of game you want to do - and on your marketing budget.
> 5 votes

# Answer
Home computers.

Nearly everyone has one, and you can release the game incrementally for free. You also have a much bigger choice on tools, and there are practically no restrictions.

---

> If I don't have an iphone/ipad or android phone, am I not able to make iphone/android game?

You can, but I wouldn't. I believe there are emulators, but it wouldn't give you the feel of the actual system.
> 3 votes

# Answer
I think mobile is larger than PCs, but they are not all smartphones. But smartphones are quicky gaining speed on PCs. Smartphone Shipments Surpass PCs for First Time. Though you can probably satisfy everyone (old browser users) with creating games using HTML5.
> 2 votes

---
Tags: platform
---


# Question
Title: Should I use OGRE3D or start from scratch with OpenGL for a large, procedural, open world game?
This question has probably been asked quite a few times, or something similar to it, but I'd like to get some better information on OGRE, since I felt that any descriptions I found weren't very comprehensive as to what it truly does.

I've been dabbling in OpenGL for a while now, and am currently doing my best to tackle shaders, with varying levels of success. Now the reason I'm learning OpenGL is ultimately to be able to develop a game, of course, but I was wondering if I could get started faster if I began using OGRE instead of programming the graphics engine from scratch.

So I looked into it, but nothing really seemed to inform me what kind of development the engine is actually good for. The game I have in mind will have a large open world, partially using procedural terrain generation, so I'm wondering how feasible is something like that in OGRE? Can it be used effectively to generate vertices in real time? Or am I better off skipping OGRE and building from scratch...

# Answer
> but I was wondering if I could get started faster if I began using OGRE instead of programming the graphics engine from scratch.

You will definitely get something up and running faster using an existing framework that works like OGRE. It's open source, so you can change things to suit your needs as they come up.

Everything I've heard about OGRE is that it's just a 3D graphics framework. It isn't really a game engine. So there (probably) isn't a lot of baggage that would make it not particular suited to one game or another.
> 6 votes

# Answer
OGRE is an abstraction layer on top of some popular graphic APIs, including OpenGL. Since the underlying API is exchangeable, you'll gain portability (same code will run on Direct3D and OpenGL ES with no or only minor changes).

On top of that, OGRE adds quite a lot of features that are useful in the daily life of graphics programming. A scene-graph, scene-managers, mesh- and animation loaders, material scripts, shaders etc. Here's an extensive list of features.

Implementing all these features alone means a ton of work. If you're interested in writing a graphics engine, then OGRE is not for you, since OGRE *is* a graphics-engine. If you want to write a game and need a robust 3D engine with lots of features, then you're definitely going to have an easier time with using OGRE instead of writing OpenGL calls.
> 7 votes

# Answer
Few months ago, I was in the exact same situation you are right now.

I was learning OpenGL and shaders etc. in order to create my own engine from scratch... And it was working very nice. But each time I needed something more for my project, I had to change a lot of stuff in the engine, because I haven't anticipated this "new" function.

Finally, I decided to use Ogre3D to create a complete game project, so I can see what functions are really important, how they are organized in the engine, or what is missing (from my own point of view) etc. And when the project will be done, I will then have the choice to keep Ogre3D as main 3D engine, or to try replacing it with my own engine using all the experience earned while using Ogre3D and all the stuffs learned before using it.

That's the reason why I recommend you to try Ogre3D or any other well established 3D engine. (I'm also considering to give a try to Irrlicht 3D to get another point of view before restarting my own engine)

---

Let's talk about Ogre3D now.

* It is not difficult to use,
* the performances are not bad,
* there is a lot of "plugins" to fits your needs...

You should take a look at the Scene Manager and particularly the Terrains to answer you questions about the terrain generation.

My main reproach about Ogre3D, is that there is tons of old examples, tons of old documentations, and tons of informations not up-to-date... but the engine itself is good and the main documentation relatively clean.
> 3 votes

---
Tags: opengl, ogre
---


# Question
Title: How do games like Minecraft generate entire worlds from a seed number?
I want to generate a completely unique world with biomes (like what Minecraft and similar games do). I don't understand how they generate these entire worlds from a single "seed" number. Can someone provide a basic overview of the technique?

# Answer
1. **How do you generate random X from a seed?** a seed value is the initial state of a random number generator. In most programming languages, you can set this seed. For example, C uses `srand()`. If you don't specify a specific seed to start with, usually a timestamp value is used as the seed. That way, each time you run, the random numbers are different.

```
// C example
srand(1);
for(i=0; i<3; i++)
    printf("%d\n", rand());
srand(1);
for(i=0; i<3; i++)
    printf("%d\n", rand());

1270216262
1085377743
1481765933
1270216262
1085377743
1481765933

```

As you can see, whenever you seed with a certain value (I used 1 as a seed), the resulting random numbers are the same.
2. **How do you create a minecraft-life world based on random numbers?** Notch has a post about this. Also, you can check out other people's tutorials on "minecraft-like worlds". I enjoyed this one, for example: Minecraft-like rendering in OpenGL 4. The basic idea is to use Perlin noise (or simplex noise). Here is a good question about noise functions: Understanding Perlin Noise
> 31 votes

---
Tags: procedural-generation
---


# Question
Title: Make my NPC "see" gameobjects around him in Unity
I have a walking NPC that will "see" the wall in front or behind him (2d gameplay) and that will react accordingly.

I was thinking to attach him to an invisible collider that would react to objects at collision, but I did not manage to do so, a collider seems to always go with a visible mesh.

How should I implement it, and how can I do it in Unity?

# Answer
> 5 votes
A common way of solving the "seeing" problem is to use raycasts.

http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html

Basically the gist of it is that you define a line starting at your NPC and going in the direction they are looking and do a trace for a certain distance with the world. You can do things like set up the world such that you're only doing traces with colliders that are marked with a certain tag (like "world").

When you get the trace information back, you know 1) if the trace hit anything 2) the object the trace hit and 3) the point at which the trace hit occurred. From there you should be able to figure out what you need to do.

# Answer
> 2 votes
I recommend using a trigger instead of a collider. Using triggers has almost no performance impact, as raycasts are very performance hungry (you should never use raycasts in the update loop). Triggers do not block movement on collision but trigger the OnTriggerEnter event.

If possible use different layers for your collides and triggers, and use the collision matrix to improve the performance and reduce unneeded collision actions.

Be aware of the collision action matrix http://unity3d.com/support/documentation/Components/class-MeshCollider.html (bottom of the page)

# Answer
> 1 votes
Colliders need not have a rendered (visible) mesh. I solved a somewhat similar problem by creating invisible targets (no rendering) with large colliders, giving the NPC (in my case, a radio tower, but this could be used to simulate something like motion detectors for a stealth game) a particle emitter, and using OnParticleCollision to script the results. Particle effects have very little overhead. When the Targets were hit by the particles (i.e. OnParticleCollision(whatHit : GameObject) ), they updated an array (each target being named as an int which was also its array index) so I could tell if all targets had or had not been hit.

---
Tags: 2d, collision-detection, unity, line-of-sight
---


title: Opengl scrolling world guidance

text:
# Question
Title: Opengl scrolling world guidance
I'm looking for a tutorial about how to implement a horizontally scrolling background with various objects that auto-scrolls as your character/player moves just like various car/motorbikes games.

I'll have images for various obstacles, objects along the path. I'm concerned if I load everything on start of game. /i would want these to be loaded for visible area as the player moves (or appears to move).

Though I'm looking for a tutorial in android and I'm new to opengl, but I welcome any sort of help.

# Answer
If your data is small enough, just load everything right into memory but be sure to cull objects that are not within the dimensions of the screen. This can be as simple as a rectangle on rectangle intersection test. Doing this will save precious time in the graphics pipeline. OpenGL must do quite a bit of work before it can safely discard invisible shapes, it's best to do this work before sending the vertices to OpenGL.

Another option is to load chunks of your level into memory, discard chunks that are no longer visible. Chunks should be at least the size of your screen to be effective (going any smaller would probably be overkill). Culling here is also important; even if you're chunk is on screen, that doesn't mean all of it will be. You would want some sort of method of detecting when a chunk is close to being in view (for example being close to the edge of a screen, but not on-screen yet). Load in a chunk when it is close enough and unload when it is far enough. Exact implementation is up to you. You could use something like a quad tree if you plan on moving on more than 1 axis (ie left-right, up-down).

Hope that helps.
> 3 votes

---
Tags: opengl, android
---


# Question
Title: What are some non-obvious topics to learn for game development?
I've been writing games for around 10 years now (from QBasic to C# and everything in-between). I need to start stretching my skills into different areas. **What are other, surprising topics I should read up on?**

Expected topics would include the usual suspects:

* Programming language of your choice
* Scripting language
* Source control
* Project management (or Agile)
* Graphics API
* Maybe some AI (A\* path-finding?)
* Physics (projectile physics)
* Unit testing (automated testing)

I'm looking for more *esoteric* topics; things that you don't expect to need to know, but if you *do* know them, they make a difference. This could include things like:

* Art skills (drawing, lighting, colouring, layout, etc.)
* Natural language processing
* The physics of sound (sound-waves, doppler effect, etc.)

Personally, I feel that having technical art skills (eg. can make decent art-work if you can only come up with ideas; or, following Photoshop/GIMP tutorials) was the most beneficial for me.

This is *not intended to be an open-ended question*; I'm looking for specific skills that helped you and you expect will continue to benefit you in the short- and long-term.

# Answer
> 31 votes
**Story Telling** \- people and critics always say story is important in games. It's often added as an addendum to a list of things your game should have, but actually implementing a compelling narrative in a game is hard. Games narratives get put into the context of literature or movies often, yet they fundamentally function differently and there is a lot of interesting discussion around about how to even talk about game narrative on its own terms. This gets even more abstract for games that don't use 'characters' or are basically an assembly of mechanics.

Given all that, literary and film analysis can be useful to be able to phrase intent.

**Marketing** \- so you've actually finished a game (haha, as if). Now what? We hear about Minecraft or Angry Birds, but the business side of actually promoting and distributing our game is, for many of us, a giant black box. XNA? Sure, put it on XBLIG, but what else can be done to promote it?

**Psychology** \- Specifically, how do we learn? How can you teach game mechanics through game play so that people aren't totally lost by your esoteric opus on time manipulation?

**Graphic Design** \- Sure we all know that using Papyrus or Comic Sans is bad, but creating a well designed menus system or UI requires skill. This is only partially a subset of art skills, not necessarily an complete subset - some people can be good designers without being able to draw well.

# Answer
> 17 votes
Having a firm grasp of world mythology and religious iconography is always good for game design. HCI and other bits of human factors psych are important just about everywhere. Being able to think like an engineer and deconstruct complex systems into smaller units is useful not just as a programmer, but also when trying to see how other games are built. Game developers tend to be a very diverse bunch, so almost any field of expertise can be used to make better games.

# Answer
> 15 votes
I am surprised that no one mentioned **maths** yet. I cannot for the life of me understand how you can be a good game developer without being good at maths.

I have seen game developers stuck with algorithm or optimisation problems, or simply writing very bad or underperforming code, because they used convolutions without knowing what an integral was, or did not know that a convolution was separable if the rank of its matrix was one, or that a composition of linear maps was linear, that the slope of a curve was related to the derivative of its function, that interpolating using `3*t^3-2*t^2` instead of `t` ensured slope continuity. I have seen them sum 50 values of `sin(x)` to approximate an area instead of using an integral. If `x` was supposed to grow to `A*x` in 10 seconds, they would set it at `A/10*x` after 1 second instead of `exp(log(A)/10))*x`. This is only what I can think of right now, but I could probably come up with dozens more of such examples.

Seriously, learn maths.

# Answer
> 7 votes
**History** \- So many successful games are based off of either true history, or adapations of it. Some of the Call of Duty series, and the Assassin's Creed series come to mind.

**Common sense** \- Yes, having something completely which implements perfectly realistic sound waves travelling through the air is nice and all that, but the user is going to struggle to see the difference. Oh, and run the game on a PC with less than a dozen GHz worth of processor power.

# Answer
> 7 votes
**Immersion** Is actually a term still being defined and discovered. What makes us immersed? Why do some people get easily immersed while others won't even flinch when playing Dead Space 2 in a dark room with loud sounds?

This subject alone has helped me a lot as it involves many psychological aspects that are great to have in mind when designing and developing games.

* **What in your game will actually** *move* **your player emotionally?** Make use of narrative immersion!
* How can you make your player stay in his or her immersion "bubble"? Make use of tactile immersion!
* What will make your player focused and think of nothing but the current challenge in your game? Make use of strategic immersion!

Check out these links for more interesting insights in to the subject:

Wikipedia article

Oldie but goldie

# Answer
> 5 votes
**Economics**

Principles learned in economics are very useful in many parts of game development. I'm not only talking about money either; economic principles apply to decisions players make about about everything from whether or not to pick up the health pack to choosing which path to take, and thus knowing economic principles can help make your game designs much stronger.

# Answer
> 3 votes
**Usability**. Designing a good and intuitive UI is actually quite *hard*, ensuring that all the info the player needs is nicely laid-out on-screen, that it doesn't obstruct the action or eat into available screen real-estate, that it's obvious when it needs to be but doesn't detract from the main scene, that the correct options are exposed in the menus, etc - that's not easy at all and takes lots of time, testing, and iterations to get right. Basic usability lessons can be picked up from almost any program, and it's well worth investing time to get right.

**Input**. This one is vitally important, and kinda ties in with usability. The graphics are the sexy stuff that people like looking at, sound gives important cues and clues, but input is the player's primary interface with the game so you'd better have really good input code. Getting a bunch of ultra-competitive multiplayer fans to road-test your engine can be quite illuminating here, not to mention humbling. You very quickly find out where your input glitches, quirks and lack of responsiveness lies.

---
Tags: education
---


title: Should game services be global? (XNA)

text:
# Question
Title: Should game services be global? (XNA)
If one wants to use services, they can use the ones built in to XNA (Game.Services) and pass around the Game object to everything that needs to either query for a service or add a service.

Alternatively, one can create their own game services class and make it static to avoid having to pass around Game everywhere.

Instead of just passing Game to everything, just to query the services (a code smell already in my opinion, just pass the services) seems a bit silly to me. Instead of passing it everywhere, why not just make a public static GameServices class?

What are the advantages and disadvantages of each approach? Which do you normally opt for?

# Answer
> 1 votes
First of all: DTSTTCPW. You probably shouldn't be using services at all. If you can send around individual objects, you should generally do that. I recommend you read my description of why services exist, on Stack Overflow.

Otherwise, if you specifically want to use services for your architecture:

The architecturally correct thing to do would be to take an `IServiceProvider` object as an argument (to which you you could pass `Game.Services`) for any object/method that needs to *consume* services. This is what `ContentManager` does.

For an object/method needs to *add* services, you should pass around `Game` (this is what XNA's `GraphicsDeviceManager`'s constructor takes, so it can add the `IGraphicsDeviceService`) or `GameServiceContainer` (which is what `Game.Services` is).

(It should be noted that the whole `Game` assembly is optional in XNA - there is no way to make an object that can add services without introducing a dependency on that assembly. `IServiceProvider` is part of the .NET framework - but it cannot be used to add services.)

It *is* "bad" architecture to make these things global. But you can do it for expediency - as long as you understand (and comment appropriately) why you are doing so. Just be mindful that you may need to "undo" this deliberately-bad architecture in the future.

(There are many reasons globals are bad architecture. Here is just one good reference.)

# Answer
> 1 votes
Because it allows a different `Game` object to be swapped out, without requiring modifying code or recompiling/reloading - the object can be changed *during runtime*.

This would allow developers to write different `Game` objects (for an online game) that come preloaded with services for development against a local dev server, and one that contains the final production server references. For example.

Using `static` classes/methods tie the invocation in the calling code to a *specific* class/method (it disables polymorphism, of course). Among other things, this makes unit testing extremely difficult. Unless the called function/class is **very** unlikely to change (like say, a `Math` library), using Dependency Injection will save a *lot* of headaches - more so if you're able to wire things at run-time, and through the use of config files.

---
Tags: xna, c#, component-based
---


# Question
Title: Rotating an object in OpenGL about it's centre
Im writing a game for which, one of the models are loaded from an `.obj` file.

It's a model of a plane, and I want to rotate the propeller. The object file is broken into groups, and the propeller is identified, so that's all good. I'm writing the game in C++ with OpenGl/GLFW The drawing function is:

```
int win_width;
int win_height;
glfwGetWindowSize(&win_width, &win_height);
float win_aspect = (float)win_width / (float)win_height;
glViewport(0, 0, win_width, win_height);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90, win_aspect, 1, 100.0);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 30.0, 0, 0, 0, 0.0, 1.0, 0.0);

glEnable(GL_DEPTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glColor3f(0.0f, 0.0f, 0.0f);
int vertexIndex = 0, normalIndex;
glRotatef(90, 0, 1, 0);
glPushMatrix();
for(int a = 0; a < (int)groups.size(); a++)
{
    if(groups[a].type == "prop")
    {
//Code for rotation
        glPopMatrix();
        glPushMatrix();
        float x,y,z;
        x = y = z = 0;
        int Count = 0;
        for(int k = 0; k < groups[a].faces.size(); k++)
        {
            for(int p = 0; p < groups[a].faces[k].vertices.size(); p++)
            {
                int _index = groups[a].faces[k].vertices[p];
                y += vertices[_index].Dimensions[_y] ;
                z += vertices[_index].Dimensions[_z];
                Count++;
            }
        }
        z /= Count;
        y /= Count;
        glTranslatef(0, -y, -z);
        glRotatef(angle, 1, 0, 0);
        glTranslatef(0, y, z);
    }
    for(int b = 0; b < (int)groups[a].faces.size(); b++)
    {
        glBegin(GL_POLYGON);
        for(int c = 0; c < (int)groups[a].faces[b].vertices.size(); c++)
        {
            vertexIndex = groups[a].faces[b].vertices[c];
            glVertex3d(vertices[vertexIndex].Dimensions[_x], vertices[vertexIndex].Dimensions[_y], vertices[vertexIndex].Dimensions[_z]);
        }
        glEnd();
    }
}
glPopMatrix();
glfwSwapBuffers();

```

Since I don't know the exact centre of the propeller, that's what the for loop before the rotation is for. It finds the average of the y and z co-ordinates.

After I find it, I translate to `-y,-z` , rotate it, and then translate back. This makes the propeller spin as I want it to, but it also rotates along the origin \>.\< http://people.sc.fsu.edu/~jburkardt/data/obj/cessna.obj \<- This is the object file.

groups is a vector of objects and each object has a vector of faces. I'm sure that the vertices and faces are being loaded correctly, since the whole model renders correctly.

# Answer
OpenGL uses a column vector convention, which means the matrices must be applied in the opposite of the order in which you actually want the transformations to occur. Just replace this:

```
glTranslatef(0, -y, -z);
glRotatef(angle, 1, 0, 0);
glTranslatef(0, y, z);

```

with this:

```
glTranslatef(0, y, z);
glRotatef(angle, 1, 0, 0);
glTranslatef(0, -y, -z);

```

and that should fix it.
> 3 votes

---
Tags: c++, opengl, 3d, rotation
---


title: The Depth buffer and Perspective

text:
# Question
Title: The Depth buffer and Perspective
I'm having trouble understanding the behaviour of my OpenGL program; and in drawing my Z-Buffer out to the screen.

It will probably be best to just start with code, here is my GLSL shader:

```
in vec3 vVertex;
smooth out vec4 vSmoothColor;

vec4 vPosition;

uniform mat4 MVP;

void main() {
    vPosition = MVP * vec4(vVertex, 1);

    float z = abs(vPosition.z);
    vSmoothColor = vec4(z, z, z, 1);

    gl_Position = vPosition;
}

```

My assumption was thus, after reading completely through the OpenGL SuperBible (blue book) and several other resources; I was under the impression the vPosition.z above should be mapped to \[-1, 1\]; which is then clamped to \[0, 1\] by the driver (assumedly).

My results were different, I expected; while using vSmoothColor as my output color; and a box moving along the Z axis from 1.f to 100.f, and the perspective matrix set up with a near and far of 1.f and 100.f, that my colors should have corresponded to the following (assuming Z mapped to \[0, 1\]):

```
Z Coord.    vSmoothColor
10          0.1, 0.1, 0.1, 1
20          0.2, 0.2, 0.2, 1
...
80          0.8, 0.8, 0.8, 1

```

Instead, my color values (ie my clipspace coordinate "vPosition.z") corresponded to almost exactly the world space Z coordinate value:

```
Z Coord.    vSmoothColor
10          10, 10, 10, 1
20          20, 20, 20, 1
...
80          80, 80, 80, 1

```

If that is the result in vPosition.z (ie the clipspace Z), how does the driver clamp the depth values for representation?

Although its been verified as correct against other implementations, here is my perspective matrix creation code:

```
inline Matrix4 perspective(float fovy, float aspect, float n, float f) {
const float t = n * tanf(radians(fovy / 2));
const float r = t * aspect;

const float d = f - n;

return Matrix4(
    n / r, 0, 0, 0,
    0, n / t, 0, 0,
    0, 0, -(f + n) / d, -1,
    0, 0, -(f * n * 2) / d, 0
);

```

}

Ref: http://www.songho.ca/opengl/gl\_projectionmatrix.html

# Answer
You haven't done the division by w. Also, the \[-1, 1\] range after projection needs to be linearly remapped to \[0, 1\], not clipped. Try this:

```
vec4 vPosition= MVP * vec4(vVertex, 1);
vec3 vPositionDivided = vPosition.xyz / vPosition.w;

float z = vPositionDivided.z * 0.5 + 0.5;
vSmoothColor = vec4(z, z, z, 1);

gl_Position = vPosition;

```

Finally, Z is not mapped linearly in a perspective projection, so you're not going to get a values like Z = 20 -\> vSmoothColor = 0.2. Instead you'll find that more of the values are concentrated close to the near plane. If you want to get linear depth, use the Z in camera space before multiplying by the projection matrix.
> 5 votes

---
Tags: opengl, depth-buffer, perspective
---


# Question
Title: Things that make a game more interesting for kids
What makes a game more interesting or fun to play for children ages 8 to 14+?

Does the age of the consumer play an important role in his/her interest in the game?

What can I put in a game to make it more fun, educational, and interesting to play?

# Answer
As the communist duck, I'd say there is a huge difference between 8 and 14. Around 12, I started wanting to build something in games, but I was too lazy for Civilization (too many things to understand), so I sticked with Sim City (cheating ; actually, I cheated regularly, not to beat the game, but to build my own story). I used to play the Warcraft "dungeon" levels, just to imagine there were castles. I would have loved minecraft at this age). Before that age, anything "new", with secrets, lots of color, constant things to attract attention worked ; after that, I grew tired of it.

So I'd say the gameplay is the variable, there : it should not be too dense, and be fairly linear (but with "secrets to discover"), before they get twelvish, and then more open-ended, giving more creativity after that. Once again, I'm basing this on my own experience, and I guess everybody is different. And it's likely that each generation is different, so trying on "real kids" would be the best idea.

A note on violence, though : I think it's less violence than power that is attractive to a younger audience. Everything you can't do in real life appeals to the player ; and there is a lot of things kids can't do : drive, have money, own a house, dress as they want, and so on... They're so powerless that every impression of power, influence, will appeal to them. This is why violence is so used in video game, because it is a pure manifestation of power (and this is why survival horror and infiltration are more subtle, and give you another view point on power).

Hope that helps !

**Edit** : Oh, and a great way to have a good answer would be to go to a local video game store and ask them what they sell to this audience.
> 4 votes

# Answer
Talk with children. Play with children. Then talk with children about their world. Talk about the games. Implement prototype. Test it with children. Iterate ... That will be fun :)

And game should have easy to learn gameplay model and that model should be based on well known "mental model" - you dont have to know physics to know how ball should fly when you kick it. Or how it looks like when somebody jumps.

*Side note: the game have to be fun even if you are not playing with children. My cousins loved my game when i was playing with them. But it was boring for them when i was gone.*
> 4 votes

# Answer
When I was about 8yo, at our school we had a simple PC game that you played by solving simple math problems (2\*4=8) etc to move the pixelated flying man to his targets on the screen. I remember having several hours of fun with that, because the math part was simple enough to become sort of automatic pretty fast. I suspect this was on purpose. :)

The key issue then, in my opinion, is to make the education you wish to pass onto the players stealthy. Kids (the majority) by definition probably feel they get enough education at their school classes already. There are however many ways the education can be slipped into the mix without them noticing. Geometry could be a very fruitful area as it is very intuitive to humans, we just have to sneak in the important aspects and the terms that we wish to pass on. Think trajectories in Worms, things involving Pythagorean theorem that is easily visualized, maybe the distinction between different triangles and how to make use of the shapes in the game etc etc..

When I was 10, I learned the English language with a dictionary at the side, so that I could understand more about civilization 1, but I was able to start to play it because the actual mechanics were very simple. I'm not sure if I qualify as mainstream enough to be a target audience though. But if you want kids to play the game, make sure that the entry skill level is low, even if the game has depth when one digs into it.

At 13 I fell in love with a puzzle game called Atomix, that taught me the structures of many important organic chemical molecules. Perhaps a reason why I'm minoring on chemistry? :) That game was lots of fun and could certainly be further improved to pass on other chemical concepts to the players without them noticing. Perhaps I'll work on this sometime..

So anyways, my hat is off to Sid, and I'm forever grateful for him for sneaking the English language and abridged world history on to me. :)
> 2 votes

# Answer
I guess violence will never get boring. Throwing ducks off a cliff seems to be very interesting.

However, when I was 10-11-12-13 I liked Myst-like games, where things had to be discovered.
> 1 votes

# Answer
You will find that education is not a good selling point. You'll never get a 10 year old to play to learn things.

Instead, like Andrei has suggested, violence works well. Make sure it's cartoon and not gore, else it'll just be unsuitable.

Give them something to laugh at, and not their own failure. Children have very little perseverance. Then again, don't make it too easy. ;-)
Cartoon characters and anything they can relate to as 'I like person X' works.

As for educational, if you can hide that behind a fun puzzle or a way to defeat some evil aliens by solving maths problems, you'll get a lot more interest.

Probably the best thing would be to make a prototype of your game (with nicer graphics) and actually get some kids to play it.
> 1 votes

# Answer
For most games, you have to *learn* playing before being actually good at them.

The most important thing (IMHO) is to keep the learning part *simple* and *fast* enough. Simple for understanding, and fast to get the player *(child)* actually involved in the game before he/she quits for another, simple/fast to get familiar *(aka 'cool')* game or other hobby.

---

**Children will love something that gently tickles their cognitive abilities *without* letting them know.**  Any game that has something related to their life (i.e. their imagination) *but* not too monotonous will be liked too.

An element of anticipation will also be good. A lot of us played games just *to get to the next level to experience it,* leading to a kind of addiction. Having a storyline or progression that rewards according to the milestones achieved is always great, like access to new arenas/castles, bonus characters, new types of questions or new environment.
> 0 votes

---
Tags: game-design, serious-games
---


title: How could I improve this random map?

text:
# Question
Title: How could I improve this random map?
following my previous post on random world map generation, I used several algorithms and obtained results similar to this: https://i.stack.imgur.com/YG26W.png (the height values are quantisied for viewing but they go from 1 to 500 before quantisation). Now I am trying to improve the "lakes", as you can see, the water bodies that are inside the map are always at 0 altitude, which means that every lake would be at the ocean level. I am willing to keep these "ocean-level lakes" (or remove them), but I would like suggestion on how to create from this heightmap real lakes that would be possibly at any height, while keeping most of the altitude structure (ie mountains positions, etc)

thanks

# Answer
> 8 votes
I don't think you really understand what you've generated here. You've created a height map. The colors only indicate how high or low something is. Blue could signify sea water level, but if you don't want to it doesn't have too. If you want lakes that are above sea level then you simply have to pick an area that is enclosed by higher ground and make water there.

# Answer
> 4 votes
Assuming that's a terrain map and not a heightmap you've generated (since I see what looks like sand, grass, snow, rock)...

See AmitP's page on procedural terrain generation. He goes into this in some detail. Of course, he doesn't use Perlin noise, but a different approach. However, the general idea is the same: You need to determine the straight skeleton, which is like an edge-centroid for a non-convex polygon such as your landmass. There are a number of ways you can go about the general idea though. Given that you have a Perlin noise bitmap, you might simply detect any land-based pixels, and determine their distance from the nearest pixel of the ocean water body *only* (not lakes). Then you will know where the "spine" of the island should lie. Using that information, you can evaluate inland lakes individually and modify the perlin noise map accordingly to create height gradients. Only once you have done this, will you be able to set your lake's water surface levels.

You don't have to throw this approach away. But you will need to do a whole lot more work if you want to turn this into a height map. Usually, Perlin is used to generate the *heightmap*, as such, and you produce the terrain types from there. But nothing says you can't do it the other way around (again, see straight skeleton formation). This would involve:

1. Use your existent terrain bitmap to generate a heightmap which is greyscale only. At this stage, you will only have two colours: Black, and one shade of grey. Your one shade of gray would represent a single uniform height across your island, black would represent the sea.
2. Using the straight skeleton, determine distance from the shore per grey pixel, and change the shade of grey to set it's height accordingly (i.e. distance from beach is very low and is a very dark gray, almost black, whereas pixels close to the spine are white).
3. You'd then need to perturb each one up or down slightly (darker or lighter shade of white) to get a more organic feel to the whole terrain.

All in all, I agree with RoyT -- It's not so easy to use what you have done as a heightmap, only as a terrain/biome map.

Re getting lake surfaces at correct heights, there are more realistic (and more complex) approaches. Fluid dynamics approaches such as cellular automata could get you a lot further in this regard.

---
Tags: algorithm, maps, procedural-generation
---


# Question
Title: Vector games (Wireframe, Elite-like) theory and implementations?
I'm interesting in knowing more about how vector games like Elite and Star Wars Atari were built from grounds up. The question is not how to implement vector graphics with modern 3D APIs like OpenGL and DirectX, since doing it is quite easy and does not require to build a vector/matrix system from scratch like those games did.

Some things I presume about these games:

* They work on an extremely low level and are written in ASM
* They're actual 3D games and not faking it like After Burner. Not like Wolfenstein 3D, either. Afterburner used rotozoom/raster effects and Wolfenstein 3D used raycasting and 2D scaling and it's not really 3D, since you can't move up. Even if you could like the Build Engine that Duke Nukem 3D used, everything except the walls is just a sprite. Star Fox is closer to it, since uses actual 3D models, but the implementation uses SNES' Super-FX chip and probably employs scanline trickery. I know Elite probably uses said scanline trickery as well (at least on some implementations like Elite NES) but I'm not sure about SWA, since it used a custom-built arcade machine; either way, I'd like to know more about it.
* Their 3D models are actual 3D models. They are defined as vectors and transformed according to the position of the camera.

I know the best thing to do would be to disassemble the source of Elite and see how things were done by myself but before doing that I want to know more about how they were made and if there are modern open-source projects that show similar techniques. I don't mean Elite remakes like Oolite (which uses OpenGL and Obj-C) but projects that use similar techniques and avoid using APIs like OpenGL directly - not necessarily low-level projects, though, using 2D library like SDL (without OGL) should be enough, at least for now.

I know that the source code to MESA3D probably contains many of the routines that games like Elite and SWA implemented - I just want to see them in the context of a game. I know that what Elite and SWA basically did was implement Rasterisation, create their format for models and a loader (I'm pretty sure that at least SWA had models built from modelers using tools, although it's not impossible to hard-code TIE-fighters it's hard to do so accurately) and many other things I may be unaware of. But it's really time-consuming to get into and I don't care about much of the stuff that is in it. Keep in mind that games like Elite were very lightweight due to the low ROM and RAM that computers and consoles had at the time.

I'm new to 3D graphics and all my assumptions are based on my limited knowledge of 3D Geometry and school level maths, sorry if I said any bullshit. But I'd really like to know more about how those games work in every detail, and possibly not just "buy X book" since I'm quite broke. Although I'd buy a book about the development of Elite or a similar game, if it existed. Some general suggestions would be enough.

# Answer
> 3 votes
> The question is not how to implement vector graphics with modern 3D APIs like OpenGL and DirectX, since doing it is quite easy and does not require to build a vector/matrix system from scratch like those games did.

Vectors are literally just a list of numbers. Matrices are just a grid of numbers. The interesting part is the mathematics you use on them, but that stuff is also trivial - just grab a school-level mathematics book where this sort of thing is explained. This is only about 50-100 lines of code, so don't overestimate the effort here.

> They're actual 3D games and not faking it like After Burner. Not like Wolfenstein 3D, either.

Wolfenstein 3D is mostly real 3D, because raycasting is arguably more 'real' than the usual geometric approach we take. Still, you're right in identifying that it's a different model and not one you're interested in here.

> I know the best thing to do would be to disassemble the source of Elite and see how things were done by myself

Don't get too hung up on Elite particularly. It's not using anything special - software rasterisation is pretty much the same no matter which piece of software did it. You take each object and transform all its coordinates into world space, then you transform all those world space coordinates relative to the viewer so that they're in view space, and then project them to 2D so they're in screen space. Each transformation is basically just a rotation and a translation, and the projection is usually little more than a division, if you make the right assumptions.

There are some other tricky bits that I can't remember immediately, like how to remove the invisible faces, but I think that can be done just with the order of the vertices - render a line between 2 connected vertices if they are clockwise in screen space, and don't if they're not. (For example.)

> it's not impossible to hard-code TIE-fighters it's hard to do so accurately

Most of those models only had about 20 or 30 vertices - easily within the realm of hard-coding. I expect the original authors drew the models on graph paper first and then copied the vertex values into the code.

# Answer
> 2 votes
You are looking for *vertex based 3D* supporting arbitrary (unrestricted) geometries in 3D space. *Raytracing* in the original sense *is* real 3D in that it may support unlimited degrees of freedom (DoF). *Raycasting* (in the game development sense rather than original sense which is similar to *raytracing* except for the direction of rays), however, restricts degrees of freedom, eg. height-map based such as that found in Comanche's voxel raycaster, or Wolfenstein which actually has the player moving in a pure 2D space. Any 3D engine that support arbitary geometries without restriction by axis is just a representation in screen space of *some sort* of model of a 3D world, irrespective of that representation.

> They work on an extremely low level and are written in ASM

In Elite's case, as you probably know, yes it was. Parts of other, similar games were cerainly written in ASM or machine code isntructions in every case, considering the demanding mathematical processing without anything like the ALUs we have today. Because there are only small parts of any codebase that are truly performance critical, it is conceivable that some less critical parts of some of these (take 3D Construction Kit and the games it made, for example) were written in C++. However, again, considering the limited resources particularly on pre 16-bit era machines, it is more like to be in a mix of assembler and raw machine code (you could actually enter huge sequences of 0's and 1's and store them to disk as a program -- heaven help you if you made a mistake).

> Their 3D models are actual 3D models

Further notes on the process of building such games from scratch:

Math, before anything else. To be authentic, you'd use fixed point math. What you can implement on the math end will determine what kind of game you can make. Period. I can guarantee you this is the philosophy Braben and Bell took to elite. Prototype, optimise, rinse and repeat. See what's possible. Then design your game around what you have made possible. This will not be the case on today's systems, as we already know (the low end of) what is possible. Find (and preferably understand the math behind -- but this is not 100%necessary) implementations of the basic building blocks: 3D vectors, rotation matrices, Quaternions (I think they favoured eulerian rotation back in the day but not certain, anyway Quaternions are cheaper to compute) and the like. Also it's key to find out what the most efficient data structures are for representing these -- *do not underestimate the impact and efficient data structure has on performance!*

Next, writing the code. Implement these structures and operations (as well as accompanying structures and logic for your broader *game*, as such) in a higher level language such as C++ or even better (faster), C. Then optimise down into asm blocks from there, as and when required. Since I'm presuming you'll want to do this on x86 or other modern architecture, this should be sufficient for your purposes. If 16 bit era hardware such as Motorola 68000-based systems, use C and refactor into ASM often. If 8-bit hardware, C is doable for limited bits, I'd think, but you will likely be refactoring mercilessly into ASM. If working on 8-bit or 16-bit systems, you ae going to have to get familiar with the architectures, the increasingly obscure tricks used on those platforms, and so on, so I wouldn't recommend this route as it is literally a dark art these days (although surprisingly there are still communities who develop for these mostly defunct systems).

Your thorough investigation of old school techniques is commendable. You're certainly going to end up with an appreciation of just how imaginably much *could* be done with the hardware we have today.

---

Some similar games I remember aside from 3DCK for you to check out:

* Dark Side
* Starglider
* Interphase
* Virus (superb little game)
* Conqueror (same engine as Virus, used to play this on a single keyboard with a buddy, one guy the tank gunner and one the driver, great memories)
* Mercenary (released just months after Elite)
* Damocles (and other Mercenary sequels and mission disks)
* Novell NetWars for x86 architecture (may even still run on something like Dosbox, though running it networked would require an authentic setup I think)

---
Tags: 3d, mathematics, matrix, vector, perspective
---


# Question
Title: 3D Flight Path Generation and applying a curve to x,y,z
I made a little critter that roams around.

```
var boundary = 10.0;
var startingPoint = <0.0,0.0>
var destination = startingPoint+<randMinMax(boundary-(boundary*2),boundary),randMinMax(boundary-(boundary*2),boundary)>;

```

It generates a random destination (x,y) within a 10 meter area around its starting point. It then moves to that point, stops, then generates a new point, turns around and faces to the new point, and continues toward it. When it reaches its destination it does the same thing over and over.

This is sufficient for just wandering around using x,y but for flight I want to implement the use of the z axis. So I modified a copy of the script to do the same thing to the z axis, with tweaks and hacks it looked alright flying around, but it appears too programmatic.

I want to take flight to the next level, now I'm not great at math, and a google search shows that 3X^2 + 4X + 6 = 0 can help me calculate a curve, I am looking for advise on how I can apply this to curve the travel when the critter reaches its destination so as to create a 'swooping' movement effect as it moves around (curved x,y,z) to its new destination. This all is begining to seem quite complicated, and I realize that the flight path cant be so random.

Has anyone got any advise for generating 3d flight paths , or assistance applying curve to x,y,z ?

Cheers

C

# Answer
For smoother-looking motion, try looking into splines, specifically Catmull-Rom splines (that link is a nice intro, and you can Google 'em; there's plenty more information on the web).

You can use the last two points and the next two points as Catmull-Rom control points and animate the creature along the spline, and the motion should be smooth. Of course this means you'll have to keep track of the last two destinations, and generate destinations two points in advance rather than one. It's just a little extra data to keep track of.
> 4 votes

---
Tags: 3d, mathematics, ai, movement
---


# Question
Title: Creating Font Textures in Direct3d without D3DX
**Update: The completed solution using Nathan Reed's answer is posted in my answer below**

A few open source programs I've seen that render installed fonts do something like this...

```
Create a texture for the font
Draw font to texture using native calls
Store the coordinates for each character
Create a vertex buffer with a quad for each character
Render the vertex buffer using the font texture

```

But I'm really having trouble getting this to work consistently. GetTextExtentPoint32A() for Win32 font sizes which does NOT include italic support and seems to cut off some of the stranger fonts.

Here is an example output from my code. Notice the cut off edge of the Q and a few other characters. A much more exaggerated version happens when rendering italics.

http://i30.photobucket.com/albums/c308/thentsc/font\_test.jpg

The code looks something like this...

```
for (uint8 c = 0; c < 127 - 32; c++)
{
    str[0] = c + 32;
    SIZE size;
    GetTextExtentPoint32A(hDC, str, 1, &size);
    if (x+size.cx+1 > m_TextureSize)
    {
        x  = 0;
        // 1 pixel vertical margin
        y += size.cy + 1;
    }

    uint32 Diff;
    ExtTextOutA(hDC, x+0, y+0, ETO_OPAQUE | ETO_CLIPPED, NULL, str, 1, NULL);
    m_fTexCoords[c].Left = x/m_TextureSize;
    m_fTexCoords[c].Top = y/m_TextureSize;
    m_fTexCoords[c].Right = x+size.cx/m_TextureSize;
    m_fTexCoords[c].Bottom = y+size.cy/m_TextureSize;

    // 1 pixel horizontal margin
    x += size.cx;
}

```

The image above is actually just a render of the whole texture stretched from -1,-1,0 to 1,1,0 not using the stored texture coordinates to show clipping due to GetTextExtentPoint32A.

Again this works fine for some fonts but looks terrible for others and doesn't support italics.

It is designed to work in a system like this...

```
cFont* g_Font;
cTextObject g_TextObject;

Setup()
{
    g_Font = SetupFont("Arial", BOLD | ITALIC, 24pt);
    g_TextObject = CreateTextObject("The quick brown fox...", g_Font, X, Y);
}

OnRender()
{
     g_TextObject->Render();
}

```

So in general I guess my question is what is the correct approach for this issue?

Should I just let each text object have a texture and on text object creation use the GDI to render all text to it (which would bypass the italics and font face problem)?

But then wouldn't texture memory usage get out of hand?

# Answer
I think your problem is that GetTextExtentPoint retrieves the "advance width", or how far the cursor would be advanced horizontally by inserting a particular bit of text. But some fonts (especially italics) contain overhangs - where the character extends a little bit further than the advance width.

You can get more detailed information by using GetCharABCWidths. This retrieves the three widths called A, B, and C; I believe the exact width of the drawn character is the B width, which should be what you want. A and C are extra space to the left and right of the character respectively, and are negative in the case of overhangs. (The advance width is A + B + C.)

If you're interested in precise typography you may also want to look at GetKerningPairs, which will tell you how to adjust the spacing when specific letters are adjacent. For instance A and V are normally slid a bit closer together when appearing adjacent: compare "AV" vs "A V". See the difference? (In the second one I put in a Unicode zero-width space character that breaks the kerning without adding any space of its own.)
> 4 votes

# Answer
Alright so after about 2 hours of coding and testing here are my findings and final solution to this problem that works perfectly for every TrueType font with any font thickness and any escapement (italics). This also works with quality CLEARTYPE\_QUALITY or ANTIALIASED\_QUALITY without AA bleeding between characters (as far as I can physically see).

This does not fix any problems with underline and strikeout not being contiguous between characters.

The major ah-ha moment was when I realized that ExtTextOutA actually prints to the screen with the negative left margin (abcA) included. This can actually result in it printing characters with their left side trimmed if you try to print them at 0 for X. You have to take this into account when rendering the characters.

Without further ado here is the solution:

```
uint32 x = 0, y = 0;
char str[2] = "\0";
for (uint8 c = 0; c < MAX_FONT_CHARS; c++)
{
    ABC* CharW = &abcWidths[c];

    // GetTextExtentPoint32 used for character height
    str[0] = c + 32;
    SIZE Size;
    if (!GetTextExtentPoint32A(hDC, str, 1, &Size))
    {
        Warning("GetTextExtentPoint32A failed for character '%s'", str);
    }

    // Left starting point is the negative left margin, it is used as an offset for ExTextOut and for calculating the Right
    uint32 Left = (CharW->abcA < 0 ? -CharW->abcA : 0);

    // The right is the Left, plus the character width, plus the left margin, plus the right overhang if it is positive
    uint32 Right = Left + CharW->abcB + CharW->abcA + (CharW->abcC > 0 ? CharW->abcC : 0);

    // Wrap around if this font would bleed off the edge
    if (x + Right > m_TextureSize)
    {
        x = 0;
        y += Size.cy;
    }

    // Draw a border where we expect the object to be drawn
    Rectangle(hDC, x, y, x + Right, y + Size.cy);

    // Print the character
    ExtTextOutA(hDC, x + Left, y, ETO_CLIPPED | ETO_OPAQUE, NULL, str, 1, NULL);
    // Store the texture coordinates
    m_fTexCoords[c].Left = x / ((float) m_TextureSize);
    m_fTexCoords[c].Top = y / ((float) m_TextureSize);
    m_fTexCoords[c].Right = (x + Right) / ((float) m_TextureSize);
    m_fTexCoords[c].Bottom = (y + Size.cy) / ((float) m_TextureSize);

    // Increment by the character width and margin
    x += Right;
}

```

The rectangle (x, y) to (x+Right, y+Size.cy) exactly matches area written by ExTextOut. I used this function in conjunction with Photoshop and some transparency to double check.

You still need to properly store and use the the abcA (Left Margin) and abcC (Right Margin) if you want to have proper overhangs and underhangs. They are intentionally used here to only find the drawn width.
> 2 votes

---
Tags: c++, directx, fonts
---