# Question
Title: Heightmap, Voxel, Polygon (geometry) terrains
In relation to Heightmap, Voxel and Polygon (geometry) terrains:

1. What are the main differences between all these three?
2. Can you form a "smooth" terrain with Voxels, I mean, can you for example get a smooth mountain with Voxels, or Voxels are limited to cubes?
3. Performance wise, a world 2000x2000 units, what would be faster Heightmap terrain, Voxel terrain or Polygon based, geometry terrain? (Assuming that there is "reasonable" performance gains/optimization done for rendering for every of possibilities)
4. Are there any more techniques used for terrain creation?
5. Any good titles representing each of types?

P.S. Polygon based terrain should be fully traingulated, no squareish stuff.

# Answer
# Heightmaps

With a heightmap, you store only the height component for each vertex (usually as 2D texture) and provide position and resolution only once for the whole quad. The landscape geometry is generated each frame using the geometry shader or hardware tessellation. Heightmaps are the fastest way to store landscape data for collision detection.

## Pros:

* **Relatively low memory usage**: You only need to store one value per vertex and no indices. It's possible to improve this further by using detail maps or a noise filter to increase perceived detail.
* **Relatively fast**: The geometry shader for heightmaps is small and runs fast. It's not as fast as geometry terrain though.
On systems without triangle based 3D acceleration, ray marching heightmaps is the fastest way to render terrain. This was referred to as voxel graphics in older games.
* **Dynamic LOD/terrain**: It's possible to change the resolution of the generated mesh based on distance from the camera. This will cause the shifting geometry if the resolution drops too far (around 0:40), but can be used for interesting effects.
* **Easy terrain generation/creation**: Heightmaps can easily be created by blending noise functions like fractal Perlin Noise and heightmap editors are fast and easy to use. Both approaches can be combined. They are also easy to work with in an editor.
* **Efficient physics**: A horizontal position maps directly to (usually) one to four positions in memory, so geometry lookups for physics are very fast.

## Cons:

* **Exactly one height per x/y coordinate**: There usually can't be holes in the ground or overhanging cliffs.
* **Less control**: You can only control the precise height of each point if the grid size matches the texture coordinates.
* **Artifacts**: If the four vertices that define a sub-quad aren't on the same plane, the split between the two vertices will become visible. This usually happens on steep cliffs with edges that don't follow a cardinal direction.

Heightmaps are the most efficient way of rendering terrain by far and are used in many newer games that don't rely on advanced terrain features and have large outdoor areas. Wikipedia has a list of programs that use heightmaps, but I'm not sure if that means they only use them as resources or also for rendering, so here a some games that are *likely* to use them:

* Just Cause 2: Regions are loaded in square sectors and there are no holes in the terrain. In the demo, there's a deep hole with stretched triangles along the edges where there normally would be a building. (The area is normally inaccessible, but there are mods to remove some of the demo's limitations...)
* Sims 2 (*maybe*): Neighborhood terrain is loaded as heightmap, but there are holes where lots (building sites) are placed. There are typical artifacts if you create cliffs on a lot, though, and it's quite tedious to add a cellar to a house (and hide the cliff under a veranda).
* Valve's Source engine games: Rectangular brushes (static level geometry) can have heightmapped terrain on their faces. In these games, the usual quirks are often hidden with other brushes or props.

It's impossible to tell for sure without looking at the shaders because every heightmap terrain can be rendered as mesh.

# Voxels

Voxel terrain stores terrain data for each point in a 3D grid. This method always uses the most storage per meaningful surface detail, even if you use compression methods like sparse octrees.

(The term "voxel engine" was often used to describe a method of ray marching terrain heightmaps common in older 3D games. This section applies only to terrain stored as voxel data.)

## Pros:

* **Continuous 3D data**: Voxels are pretty much the only efficient way to store continuous data about hidden terrain features like ore veins.
* **Easy to modify**: Uncompressed voxel data can be changed easily.
* **Advanced terrain features**: It's possible to create overhangs. Tunnels are seamless.
* **Interesting terrain generation**: Minecraft does this by overlaying noise functions and gradients with predefined terrain features (trees, dungeons). (Read Terrain Generation, Part 1 in Notch's blog for more info. There is no part 2 as of 05.8.2011.)

## Cons:

* **Slow**: To render voxel data, you either have to use a ray tracer or compute a mesh, for example with marching cubes (There will be artifacts). Neighboring voxel aren't independent for mesh generation and the shaders are more complicated and usually produce more complex geometry. Rendering voxel data with high LOD can be very slow.
* **Huge storage requirements**: Storing voxel data uses **lots of memory**. It's often not practicable to load the voxel data into VRAM for this reason, as you'd have to use smaller textures to compensate for it, even on modern hardware.

It's not practical to use voxels for games that don't rely on voxel features like deformable terrain, but it can allow interesting game mechanics in some cases. Voxel engines are more common in older games, but there are also newer examples:

* Atomontage engine: Voxel rendering.
* Worms 4: Uses "poxels". According to Wikipedia it's a mix of voxels and polygons.
* Minecraft: Uses voxel to represent the terrain in RAM, the graphics are polygon graphics. It's mostly software calculated though.
* Terraria: An example for 2D voxels. I don't know how it renders.
* Voxels combined with physics: Not a game. but it nicely showcases the destruction potential.
* Voxatron: A game using voxels for almost all of the graphics, including menus and HUD.

# Meshes

Polygon meshes are the most flexible and precise way of storing and rendering terrain. They are often used in games where precise control or advanced terrain features are needed.

## Pros:

* **Very fast**: You only have to do the usual projection calculation in the vertex shader. A geometry shader isn't needed.
* **Very precise**: All coordinates are store individually for each vertex, so it's possible to move them horizontally and increase mesh density in places with finer details.
* **Low memory impact**: This also means the mesh will usually need less memory than a heighmap, because vertices can be more sparse in areas with less small features.
(See Triangulated irregular network on Wikipedia).
* **No artifacts**: The mesh is rendered as-is, so there won't be any glitches or strange-looking borders.
* **Advanced terrain features**: It's possible to leave holes and create overhangs. Tunnels are seamless.

## Cons:

* **Poor dynamic LOD**: Only possible with precomputed meshes. This will cause "jumps" when switching without additional data to map old to new vertices.
* **Not easy to modify**: Finding vertices that correspond to an area that should be modified is slow.
* **Not very efficient for collision detection**: Unlike in heightmaps and voxel data, the memory address for a certain location usually can't be calculated directly. This means physics and game logic that depend on the exact surface geometry will most likely run slower than with the other storage formats.

Polygon terrain is often uses in games that don't have large open areas or can't use heightmap terrain because of its lack of precision and overhangs. I don't have a list, but I'm pretty sure that

* every 3D Zelda and
* every 3D Mario game

use this.

# Other methods

It's possible to create a terrain entirely in the shader pipeline. If the algorithm runs only in the fragment/pixel shader, the detail can be virtually unlimited while memory impact is almost zero. The obvious downsides are almost no control over the shape and problems when the camera intersects the original rendering surface. It's still useful in space games where players don't interact with the surface of a planet. Parameter animations work best with this kind of terrain.

It should be possible to download the generated terrain geometry from the graphics card to use it for the rest of the game engine, but I don't know how the performance of that is or whether this has been done so far.

# Conclusion

There is no method that works well for every scenario, but it's fairly easy to choose one for a certain task:

* **Heightmaps** are the best solution if you don't need overhangs or holes in the terrain surface and use physics or dynamic terrain. They are scalable and work well for most games.
* **Meshes** have the highest precision and can describe overhangs, holes and tunnels. Use them if you have complex terrain that doesn't change often.
* **Voxels** are good for describing very dynamic terrain with many complex features. Avoid rendering them directly as they need large amounts of memory and processing.
* **Other methods** may be better than any of the above if you don't have to interact with the terrain or need very detailed graphics. They usually work only for very specific scenarios.

It's possible to combine different methods to get features from more than one, for example by tessellating mesh terrain with a heightmap to increase the detail structure of a cliff.

Dynamic terrain generation is heavily used in procedural space simulation and some have become really advanced in the last years. The forums of these projects should have some resources on the topic.
> 34 votes

# Answer
I'd like to point out that none of the terms you mentioned are mutually exclusive with each other - you could even have a voxel based game that used heightmaps and rendered using polygons.

1. Height-maps are two-dimensional representations of the height of the ground at each specific point. They are often stored as greyscale images, where the brightness represents the height of that point. Voxels are basically a 3D bitmap. There are a variety of techniques used to render a voxel space.
2. You can create a smooth terrain with voxels, and they aren't limited to cubes. One such way is to use an algorithm like marching cubes, which can convert a voxel representation into a polygon list.
3. The one with the least triangles would render the fastest :3
4. Fractal algorithms such as Perlin noise can be used to create landscapes with a lot of
detail. Parametric surfaces such as nurbs can be used to create smooth terrains with little permanent storage requirements.
5. Delta Force is an old game that uses voxels. Minecraft may use voxel storage to represent the landscape (unsure). Sacrifice by Shiny is a game that uses heightmaps to good effect. Most games with landscapes use geometry terrains.
> 9 votes

---
Tags: level-design, terrain-rendering, terrain
---


# Question
Title: Is my "engine" development process ideal?
I was thinking about a game engine development, I understand as engine the main program that can develope next duties:

1. Receives parameters.
2. calculates what is needed.
3. Delivers results.

As an example lets say I'm writing an sports game, so I was thinking that instead of starting with something big I could start with a very small objectives and always (now not even thinking in graphics management so maybe I could be speaking about a simulation and not yet even about a game) just getting data result through the shell.

What about next steps?

1. Develop an script which gets all the data stored in a database and after calculating everything based on that data it releases the result of the match or race.
2. Get more in detail and a part of calculating the result it delivers too details through the match or race (not jet in real time).
3. In that third stage what it happens is that the program will temporize the details and final result progress in real time through the shell delivering messages before the final result.
4. Though the real time data delivering the user will be available to interact introducing parameters when is asked.

Many thanks I hope it gets your interest, I'm just trying to clarify the process and catch advice and suggestions from experienced people.

# Answer
As far as I understand - *and I'm not sure to have understood right* \- you are describing something like a test-driven developing system.

If it is your case you should focus on: adding a functionality, test for (some sort of) correctness, test it does not break existing functionalities, profile it, tune performace.

Your engine should be a kind of library that has the responsibility to abstract a complexity. What are the complexities on your game? How can those breaked down into decoupled ones? How each complexity can be abstracted throught functionalities?

What you described should be seen into a process of testing the incremental adding of functionalities. In this scenario you can use mock data so you can foresee the results and mantain the functionalities decoupling.
> 0 votes

# Answer
In the title you are talking about engine development but, there in only 1-2 lines of actual engine development talk. Most of the thing that you've talked about is the logic part of the game, which in *not related to engine development*.They are related to game logic, which varies from game to game.

Nonetheless, just for the title's sake I am going to put my cent here, cause I am also working on my own game engine right now.

Game engine is an library which you develop to handle the game logic and assets. As anything else out there, there is not ideal process of developing a game engine. Whenever you want to develop a game engine, I can safely assume that you have worked(or have some idea) with several game engines before and now you want to make one of your own. In my case I am a big fan of jMonkey Game Engine and I am trying to mimic that engine in C++(jMonkey is Java based). Why copy instead of new architecture, for 2 reasons. I can use their architecture, cause they are developing it for years so, there should be a reason why they choose it.Rather then creating something new on my own from the scratch, and later finding it's not good for implementing certain feature. Another reason is the documentation will be same ;)

So, first what I did is gathered enough knowledge about Opengl and java to read through the jMonkey source code. They I am trying to abstract out the important parts which can work independently. Say, you are going to drop the *Game State* & *Render Manager* part. Just the object loading & setting up material should be enough for prototype 0.1.

Then add other features. You will find problem while adding new features to the existing code. You may end up with re-writing the major part of your code but you will learn a lot about what-shouldn't-be-done along the way. From here, its a iterative process. After a certain point, you'll find yourself in a position when you can think about your own engine without looking into other engines. That's when things get a lot of fun.

Hope it helps someway.
> 0 votes

---
Tags: process
---


# Question
Title: Android NDK - moving .so files from one project to another
I have a small project I've coded for Android that uses a small about of NDK/JNI code. I'd like to share this code between two projects but I'm having little luck so far. First off, I've tried to refactor off the NDK specific code into a library which I think link to both projects using

'project-\>java build path-\>source-\>link source'

and specifying the native library in there. Sounds good but it's wrong. The project from which I refactored the code still requires the .so library file in

MyOriginalProject\libs\armeabi\MyNativeLibrary.so

Removing that from the original project whilst still linking the source of the refactored library fails.

Secondly, creating a new project and attempting to use the NDK library I wrote by both including the source of the library and copying over the .so files from 'obj' and 'libs' into the root directory of the new project fails. It seems to pass

System.loadLibrary("MyNativeLibrary")

At least, it didn't assert.

The code gets as far as my first NDK call and then crashes without being caught by my exception handler.

Any hints would be welcome - such as foolproof ways to get NDK to load a library, typical gotchas and NDK debugging techniques.

Thanks in advance,

Tim.

# Answer
> 2 votes
When I worked with the NDK a year ago, I build the .so file with the NDK make. Then I copied the .so from the NDK to the /lib folder of my project. It worked without a problem. Do the method names in your NDK-Project match the fully qualified class-/methodnames of the classes where you want to call the JNI functions? If you have a class:

```
package com.example;
 public class Foo{
  native public void bar();
 }

```

Then the method in your C file must be something like:

```
void com_example_Foo_bar();

```

If that didn't help, could you then post the exception?

# Answer
> 0 votes
Solved it - the missing signature was a bug in the C++ code that didn't manifest in the other project as that function was never called. Just a miss named function signature, that's all.

---
Tags: java, android, ndk, jni, eclipse
---


# Question
Title: Zelda LttP (Super Nintendo) room changes?
I'm trying to make a tile-world adventure game on iOS similar to Zelda Link to the Past on SNES, and one issue I've run into is having my camera move beyond walls revealing the rooms on the other side. I like the way Zelda handled room changes where once you went through a door the screen would slide over to show the new room, but I can't figure out how they did it. I'm using Obj-C on my own tile-world engine, so I'm more interested in logic than code, but anything would help.

I'd also be interested to hear any alternative suggestions for limiting the movement of the camera. (Presently I have the position of the camera restricted to the bounds of the level being drawn, but in order to reduce loading I've decided to increase the size of levels to put multiple rooms/floors on the same map.)

**Edit** One of the key things that the transition I am asking about offers is the ability for the player to leave the center of the screen. I think that you lose a sense of motion or progress when the player is always dead center in the screen. My camera is designed to stop moving at the world bounds, but I'm having trouble figuring out how to define 'room bounds' within a world for the camera to stay within until triggered to move.

I also recognize how transitions break up gameplay, but when you're dealing with a top-down 2D adventure game, if you want to conceal the contents of the next room over and also allow for some range of motion free of the camera, I'm not sure what better way there is.

# Answer
> 1 votes
Some games of this sort, especially ones with single-screen non-scrolling rooms (but also many with scrolling rooms!) don't actually move the camera over to the next room. They move the next room over to the camera. The math to do so is trivial but quite a few lines of code, but you can imagine the new room "pushing" the old one out of the way. If that then places the camera in a weird place, you can reset the position of the camera and the new room in one impossible-to-notice step.

If you're working in 2D and only loading a room at a time, you shouldn't have to worry about load times.

# Answer
> 0 votes
The 2d Zelda games likely had a set of points (basically a rectangle) that contained the 'max scroll' limits on the camera, and when Link walked to a different room, it would move the camera and change where those points were set. If you've already got bounds on the camera, then you can likely add these sort of room transitions without too much work. During transitions, disable player input and quickly move the camera in the direction you want, then return control to the player.

Pointless extra trivia time: Link's Awakening (and likely the other 2d zelda games) contained only a few maps that contained many different rooms, along the overworld and caves and dungeons mixed together (there's examples of this out on the internet, but I can't seem to find them right now). I believe Link's Awakening in particular had 3 maps total, and many transitions would simply warp you to a different spot on the same map.

# Answer
> -1 votes
This is easy. The most obvious logic would be:

* Calculate camera viewport bounds and convert them to the world coordinates with current camera translation.
* Check resulting "camera bounding rectangle" with bounds of the current room and forbid further camera movement if needed.
* When your game charater moves onto a door trigger move camera to the next room.

**The real question is, do you really want to break player's game flow after each room?** This day and age there are lots of memory, and it's possible to avoid such form of a loading screen which slows down and irritates a player. Rarely a game can incorporate loading transitions into its atmosphere, like doors in the Resident Evil or Parasite Eve, end even then it's a mild annoyance.

I can't see your game world, but maybe other techniques which wont require waiting for a transition to end can be used, like fog of war, room roofs, vague silhouettes or some other form of "terra incognita"?

---
Tags: 2d, maps, camera, loading
---


# Question
Title: Using PS3 controller for input on Mac OSX
I've managed to find a USB driver to connect to the PS3 controller in OSX, and as reported here, can connect to the controller via Bluetooth.

I've verified that the input is working properly via Snes9x.

Anyway, that's just background for my *actual* question. Is there any way to access the PS3 HID, via C++, on the Mac? I'm relatively new to C++ development on Mac using XCode, and the internet has been disappointing in my search for a possibly library to use.

Does anybody have any ideas on how I could access the controller button/axis states in code, so I can transfer them to my input maps?

# Answer
So, an hour or so of fiddling and trying different libraries, and it seems OIS (and SDL) just recognises the controller as a joystick and provides me with everything I need.

If you install OIS from the link above, and make/run the 'ConsoleTest' project, you can see the output from the controller in the debug window.

---

Additionally, here's enums i've been using that match to the axes/button numbers produced by **SDL** (note not OIS, which i've now decided not to use, numberings could well be the same). Notice that the trigger buttons are not classified as an axis, which i'm pretty sure they should be (0-255 from memory):

```
//Values SDL attributes to individual PS3 axes
enum EPS3RawAxesIndex
{
    EPS3RawAxesIndex_LeftX = 0,
    EPS3RawAxesIndex_LeftY = 1,
    EPS3RawAxesIndex_RightX = 2,
    EPS3RawAxesIndex_RightY = 3
};

//Values SDL attributes to individual PS3 controller buttons
enum EPS3RawButtonIndex
{
    EPS3RawButtonIndex_Select           = 0,

    EPS3RawButtonIndex_JoyClickLeft     = 1,
    EPS3RawButtonIndex_JoyClickRight    = 2,

    EPS3RawButtonIndex_Start            = 3,

    EPS3RawButtonIndex_DpadUp           = 4,
    EPS3RawButtonIndex_DpadRight        = 5,
    EPS3RawButtonIndex_DpadDown         = 6,
    EPS3RawButtonIndex_DpadLeft         = 7,

    EPS3RawButtonIndex_TriggerLeft      = 8,
    EPS3RawButtonIndex_TriggerRight     = 9,

    EPS3RawButtonIndex_ShoulderLeft     = 10,
    EPS3RawButtonIndex_ShoulderRight    = 11,

    EPS3RawButtonIndex_Triangle         = 12,
    EPS3RawButtonIndex_Circle           = 13,
    EPS3RawButtonIndex_Cross            = 14,
    EPS3RawButtonIndex_Square           = 15,

    EPS3RawButtonIndex_PSButton         = 16
};

```
> 4 votes

---
Tags: c++, input, playstation3, macos
---


# Question
Title: What's a good alternative to buying a console devkit?
I don't have the cash to stump up for a PS3 or 360 devkit, but the G3, G4 and G5 macs are running with PowerPC chips, which I believe is virtually the same architecture as the 360, and only missing the SPUs from the PS3, so I would like to know which Macs would be good for profiling code with.

I'm after a machine that would give me equivalent timings (not actual timings, but scale the same given difference code) so I'm looking for ones that have about the same cache size and memory bandwidth ratios as the consoles. Are there any specific Macs that have these traits?

The reason I need one is that I'm developing a new programming language for games development that specifically targets the current and potential future of console hardware. One aspect of this is the in-order microcode expanding risc chips at the core of both the 360 and the PS3, and probably the next generation too, which is why I want a PPC based mac, as I'd heard that places like where I work used to use Macs as pretend 360 devkits until the hardware design was in a fit state to send out prototype 360s.

At a later date, I'll want to get my hands on an FPGA (as that's the only other route I can see consoles heading any time soon), and a cluster (as they are good practice for ensuring your task scheduling and separation are up to scratch), but for now I just need to know if there is a sweetspot machine that had very similar specs to the current consoles' CPU and memory bandwidth.

# Answer
> 11 votes
If you want to develop native games for 360/PS3, there is no alternative to getting a Devkit.

Consoles are more than just a CPU. It's graphics card, OS, memory, File-System, SDKs and a lot more. If your idea is to port later, thats not gonna work as easy as getting a more less similar machine in terms of its specs. The entire environment is different to a normal PC/Mac, not to mention the certification process (TRC/TCR) by Sony/Microsoft before you can actually release your game. You should be aware of the certification requirements before writing too much code.

If your plan is to develop for consoles, focus on them right from the beginning. But most likely you won't get Devkits, its not as simple as just ordering them. So the whole getting-a-similar-system-idea renders useless from different angles.

# Answer
> 3 votes
In order to get on the Xbox you can start out making a PC game using XNA, and if it's good it shouldn't be a big problem to get the right permissions so that you can port it to Xbox 360. If you are on the "a dev kit is probably too expensive" stage, don't even bother considering the PlayStation 3 a potential target platform.

# Answer
> 2 votes
In addition to what Maik said, you'll struggle to find something with the same performance profile as the Xbox 360 CPU. From the public version of the hardware spec on Wikipedia (as the XDK stuff is under NDA) you can see that the CPU is "in-order" execution where most if not all "desktop" CPU's. This one big difference can make a massive difference to the performance profile of the CPU alone, let alone the way all the different systems are hooked together. It completely changes the way the code needs to be optimised because of the way any stalls now affect the speed the CPU executes code. The CPU also includes custom logic for performing vector operations you won't find elsewhere.

It's also not as simple as just "having enough money" to buy a devkit. You'll also need to show MS you have a decent enough concept and also probably more discussion before they'd let you licence one.

# Answer
> 0 votes
MS offers its development stack for the 360 (XNA Game Studio, Expression Blend) for free. And they also offer a pretty cheap entrace to market via Xbox live

# Answer
> 0 votes
There is no alternative to actually organising the tests and then running them on final hardware. A Mac has

> "a completely different performance profile from the final kits (in both the CPU, GPU and other components)"

So, I should just work on the project until such time as I can get access to the hardware then submit a set of tests and get profiles back and iterate like that until I'm happy with the state of the project.

Please vote to close as this question is too limited in use to anyone.

---
Tags: xbox360, playstation3, macos
---


# Question
Title: What's efficient way to draw a lot of textured cubes in XNA4?
Title says it all.

What's efficient way to draw a lot of textured cubes in XNA4?

# Answer
> 7 votes
I guess it is for another minecraft-inspired game, so "a lot" means several million cubes :) Well, be it minecraft, warcraft, XNA, OGL or whatever else, the task of drawing "a lot of anything" consists of two parts:

* Reducing the size of the task.
* Making the actual drawing efficient.

It's possible to write an entire book about these problem facets, so let's keep it simple.

**How to reduce the amount of the cubes you need to worry about?** Use octrees and perform frustum culling for visibility determination.

**How to optimize the draw method for lots of cubes?** Large number of cubes (maybe even all of them depending on your approach) will share the same material, so it will be easy to utilize instancing.

Then again, depending on how much "a lot" actually is, you may want to stop caring about rendering optimizations at all. With the modern hardware you can draw like ten million of textured cubes easily with almost no hassle: just divide them into large chunks and draw with basic batching and a simple index buffer.

# Answer
> 0 votes
Have a look at this SunBurn instancing example: http://indiefreaks.com/2011/01/27/hardware-instancing-with-igf-sunburn-rd-part-1/ and then part 2 http://indiefreaks.com/2011/01/28/hardware-instancing-with-igf-sunburn-rd-part-2/ It handles massive amounts of instanced objects.

---
Tags: xna, textures, xna-4.0, efficiency
---


# Question
Title: How did EA DICE create destructible environments in Battlefield Bad Company 2 and Battlefield 3?
How did the folks at EA DICE create destructible environments in Battlefield Bad Company 2 and Battlefield 3?

Did they just assemble the buildings out of predefined sub-regions, that break apart when there is an explosion or something similar? I can't think of anything else.

# Answer
> 28 votes
To put it simply yes that what they do. But the go an extra length to cover up the straight edges using *destruction mask*. After removing the part of the geometry, they add *detailed mesh* around the destroyed section to make it look believable.

Here is how it works,

When destroying a part of this house, they begin by removing a piece of the geometry

Then added detail meshes around the destroyed section.

And the final step is to add the destruction mask.

They also use particle effects and mesh debris for more dramatic look.

*(All the reference is taken from those 2 publications I mentioned in the comment)*

# Answer
> 9 votes
This is CSG -- Constructive Solid Geometry (although in this case, it's destructive, strictly speaking), if you want to do more research on how the algorithms actually work.

The standard approach is to use the two existing meshes A & B (the house and the subtracted "explosion" volume) to generate a third "mesh" (graph) where the two meshes planes and edges intersect, C -- which describes the area they share. In 2D:

```
      / \
     /   \
    /  A  \
     |   |
     | /-|-\
     | |C| |
---  ----- | ------- G
       |  B|
       \---/

```

A is the house, B is the is the explosion volume, C is the union / intersective area between A and B. G is the ground.

The mathematics / logic behind it is not trivial, as there are many edge cases to deal with and half or more of this task is just recognising which of the possible types of outcome graphs are special cases which need to be catered for in code. I've seen the problem described by the veterans on gamedev.net as "a very hard problem" and I can tell you from attempting it in 2D, even, and having a moderate degree of success where only a couple of edge cases fail, that it is no small task.

A way that might be easier is to use a polygon decomposition algorithm, and use the geometry that creates as a basis for your geometry destruction instead.

---
Tags: physics
---


# Question
Title: Displaying 2 textures on the same surface?
I'm messing around with XNA in a very simple Minecraft-esque world I'm making and I'm wondering how I can do the "breaking the block" visuals in XNA.

If you're unfamiliar with the game, you begin interacting with the cube and based one what tool you're using, the block will take X amount of time to break. There's about 10 different stages of cracking that the cube will display before the cube breaks. I'm curious about how to display those 10 stages of cracking on top of the original skin of the block.

I know the game works using a Sprite sheet to color the blocks. This sprite sheet does not include every possible design at every possible stage of breaking the block, each stage is a different sprite with some transparency.

In short, how can I quickly and efficiently overlay a texture on a surface that already has a texture?

Do I have to combine them? If so, how?

# Answer
Use XNA's `DualTextureEffect` when drawing your block. It's a standard shader that lets you overlay one texture in top of another. Just use the same base texture and overlay different cracking textures in top of the other.
> 5 votes

# Answer
If you want to do it in an effect of your own, there's two common ways of doing it.

* Bind two textures and make a sample from both of them, followed by multiplying or adding them together in the pixel shader while computing the output colour.
* Write an effect with multiple passes (assuming that XNA supports it), where the first pass draws the base opaque texture and the second pass draws the overlay texture with multiplicative or additive blending.
> 3 votes

---
Tags: textures
---


# Question
Title: Downprojecting an imaginary 4D mesh to the screen
As a mental exercise, I'm trying to imagine projecting an arbitrary 4D mesh onto the screen (2D).

I'm guessing a single 4D triangle would still consist of only 3 points, however each of those 3 points would be defined by column with 4 dimensions.

Would it make more sense to define a projection matrix to map 4D space to 3D space first and then have OpenGL do its own projection from that data to 2D space?

Or would it be best to just plan on projecting down from 4 to 2 directly?

Many thanks.

# Answer
The multidimensional generalization of a triangle is an N-Simplex, here is a video of a projection of such an object. Here is another interesting video of a 4D hypercube.

This wiki page is a good starting point if you want to learn more about the fourth dimension and how to visualize such objects. It also links a wiki page with a list of 4D games.

Regarding your question about the projection: This paper explains the math of orthographic and perspective projection matrices for higher dimensions. Another great paper is Four-Space Visualization of 4D Objects by Steven Richard Hollasch. Particularly the paragraph "4.1: High-Level Overview of 4D to 2D Projection" answers your projection question in detail and comes with source code.

Finally here is an N-dimensional renderer using OpenGL coming with full source code.
> 8 votes

---
Tags: matrix, vector, projection
---


title: Optimizing perlin noise generation

text:
# Question
Title: Optimizing perlin noise generation
I have a perlin noise generator as shown below.

```
public class ImprovedNoise
{
    private const int GradientSizeTable = 256;
    private readonly Random _random;
    private readonly double[] _gradients = new double[GradientSizeTable * 3];
    /* Borrowed from Darwyn Peachey (see references above).
       The gradient table is indexed with an XYZ triplet, which is first turned
       into a single random index using a lookup in this table. The table simply
       contains all numbers in [0..255] in random order. */
    private readonly byte[] _perm = new byte[] {
          225,155,210,108,175,199,221,144,203,116, 70,213, 69,158, 33,252,
            5, 82,173,133,222,139,174, 27,  9, 71, 90,246, 75,130, 91,191,
          169,138,  2,151,194,235, 81,  7, 25,113,228,159,205,253,134,142,
          248, 65,224,217, 22,121,229, 63, 89,103, 96,104,156, 17,201,129,
           36,  8,165,110,237,117,231, 56,132,211,152, 20,181,111,239,218,
          170,163, 51,172,157, 47, 80,212,176,250, 87, 49, 99,242,136,189,
          162,115, 44, 43,124, 94,150, 16,141,247, 32, 10,198,223,255, 72,
           53,131, 84, 57,220,197, 58, 50,208, 11,241, 28,  3,192, 62,202,
           18,215,153, 24, 76, 41, 15,179, 39, 46, 55,  6,128,167, 23,188,
          106, 34,187,140,164, 73,112,182,244,195,227, 13, 35, 77,196,185,
           26,200,226,119, 31,123,168,125,249, 68,183,230,177,135,160,180,
           12,  1,243,148,102,166, 38,238,251, 37,240,126, 64, 74,161, 40,
          184,149,171,178,101, 66, 29, 59,146, 61,254,107, 42, 86,154,  4,
          236,232,120, 21,233,209, 45, 98,193,114, 78, 19,206, 14,118,127,
           48, 79,147, 85, 30,207,219, 54, 88,234,190,122, 95, 67,143,109,
          137,214,145, 93, 92,100,245,  0,216,186, 60, 83,105, 97,204, 52};

    private static ImprovedNoise instance;
    public static ImprovedNoise Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new ImprovedNoise((int)DateTime.Now.Ticks);
            }
            return instance;
        }
    }

    private ImprovedNoise(int seed)
    {
        _random = new Random(seed);
        InitGradients();
    }

    public double Noise(double x, double y, double z)
    {
        /* The main noise function. Looks up the pseudorandom gradients at the nearest
           lattice points, dots them with the input vector, and interpolates the
           results to produce a single output value in [0, 1] range. */

        int ix = (int)System.Math.Floor(x);
        double fx0 = x - ix;
        double fx1 = fx0 - 1;
        double wx = Smooth(fx0);

        int iy = (int)System.Math.Floor(y);
        double fy0 = y - iy;
        double fy1 = fy0 - 1;
        double wy = Smooth(fy0);

        int iz = (int)System.Math.Floor(z);
        double fz0 = z - iz;
        double fz1 = fz0 - 1;
        double wz = Smooth(fz0);

        double vx0 = Lattice(ix, iy, iz, fx0, fy0, fz0);
        double vx1 = Lattice(ix + 1, iy, iz, fx1, fy0, fz0);
        double vy0 = Lerp(wx, vx0, vx1);

        vx0 = Lattice(ix, iy + 1, iz, fx0, fy1, fz0);
        vx1 = Lattice(ix + 1, iy + 1, iz, fx1, fy1, fz0);
        double vy1 = Lerp(wx, vx0, vx1);

        double vz0 = Lerp(wy, vy0, vy1);

        vx0 = Lattice(ix, iy, iz + 1, fx0, fy0, fz1);
        vx1 = Lattice(ix + 1, iy, iz + 1, fx1, fy0, fz1);
        vy0 = Lerp(wx, vx0, vx1);

        vx0 = Lattice(ix, iy + 1, iz + 1, fx0, fy1, fz1);
        vx1 = Lattice(ix + 1, iy + 1, iz + 1, fx1, fy1, fz1);
        vy1 = Lerp(wx, vx0, vx1);

        double vz1 = Lerp(wy, vy0, vy1);
        return Lerp(wz, vz0, vz1);
    }

    private void InitGradients()
    {
        for (int i = 0; i < GradientSizeTable; i++)
        {
            double z = 1f - 2f * _random.NextDouble();
            double r = System.Math.Sqrt(1f - z * z);
            double theta = 2 * System.Math.PI * _random.NextDouble();
            _gradients[i * 3] = r * System.Math.Cos(theta);
            _gradients[i * 3 + 1] = r * System.Math.Sin(theta);
            _gradients[i * 3 + 2] = z;
        }
    }

    private int Permutate(int x)
    {
        const int mask = GradientSizeTable - 1;
        return _perm[x & mask];
    }

    private int Index(int ix, int iy, int iz)
    {
        // Turn an XYZ triplet into a single gradient table index.
        return Permutate(ix + Permutate(iy + Permutate(iz)));
    }

    private double Lattice(int ix, int iy, int iz, double fx, double fy, double fz)
    {
        // Look up a random gradient at [ix,iy,iz] and dot it with the [fx,fy,fz] vector.
        int index = Index(ix, iy, iz);
        int g = index * 3;
        return _gradients[g] * fx + _gradients[g + 1] * fy + _gradients[g + 2] * fz;
    }

    private double Lerp(double t, double value0, double value1)
    {
        // Simple linear interpolation.
        return value0 + t * (value1 - value0);
    }

    private double Smooth(double x)
    {
        /* Smoothing curve. This is used to calculate interpolants so that the noise
          doesn't look blocky when the frequency is low. */
        return x / 1.25; //* x * (3 - 2 * x);
    }
}

```

I use this algorithm by doing threshold detection (at specific values, it will generate tiles, at other values it won't). However, the results I have right now are not as I intend them to.

I would like more "space" between the "walls". Scaling is not an option, because I like the size of the tiles now.

See my attached screenshot below.

# Answer
The easiest way I can think of is simply adjusting the threshold parameter, a smaller value would result in thicker walls, while a higher value would result in thinner walls (or vice versa, depending on your threshold test)
> 4 votes

# Answer
> I would like more "space" between the "walls". Scaling is not an option, because I like the size of the tiles now.

If you want to change the scale of your noise, rather than scaling your tiles up or down, you can scale the coordinates where you sample the noise. So, instead of sampling the noise at `Noise(tile.x, tile.y, z)`, sample at `Noise(tile.x * scaleX, tile.y * scaleY, z)`. You can also change the threshold value for deciding what's a wall if you want to make the walls thicker or thinner with the same scale noise.
> 0 votes

---
Tags: xna, c#, terrain-rendering, terrain
---


# Question
Title: Perlin noise - copying the algorithm on the CPU?
I have successfully made a Perlin noise algorithm on the GPU. It works as expected, and generates great results. Now, as part of the physics calculations in my game, I need to replicate the exact same algorithm on the CPU, so that I can (given an X, Y and Z coordinate) determine whether or not that is inside a wall, or a walkable area.

I have debugged the shader through PIX, and I've gotten everything almost right, except for the part below (seen in shader code).

**GPU (shader) code (HLSL)**

```
float4 perm2d(float2 p)
{
    return tex2D(permSampler2d, p);
}

```

permSampler2d samples a texture that I generate out of Color structures and then pump to the GPU. The way I generate the texture on the CPU is the following:

**CPU code (XNA C#)**

```
int createPerm2d(int i)
{
    return permutation[i % 256];
}

public Texture2D GeneratePermTexture2d()
{
    permTexture2d = new Texture2D(device, 256, 256, true, SurfaceFormat.Color);
    permutationData = new Color[256 * 256];
    for (int x = 0; x < 256; x++)
    {
        for (int y = 0; y < 256; y++)
        {
            int A = createPerm2d(x) + y;
            int AA = createPerm2d(A);
            int AB = createPerm2d(A + 1);
            int B = createPerm2d(x + 1) + y;
            int BA = createPerm2d(B);
            int BB = createPerm2d(B + 1);
            permutationData[x + (y * 256)] = new Color((byte)(AA), (byte)(AB),
                                            (byte)(BA), (byte)(BB));
        }
    }
    permTexture2d.SetData<Color>(permutationData);
    return permTexture2d;
}

```

As said before, all this works as expected, until I run the code on the CPU to get the noise data back later.

According to PIX, the part that fails is indeed perm2d on the CPU (as seen below), which produces incorrect results.

**CPU code (XNA C#)**

```
static Vector4 perm2d(Vector2 p)
{
    return permutationData[(int)p.X + ((int)(p.Y) * 256)].ToVector4();
}

```

At the particular area (in the exact same pixel with the exact same seed used to generate the map, where it returns the incorrect results, PIX reports that the GPU returns "{0.035, 0.067, 0.365, 0.408}" from the perm2d function whereas the CPU code returns "{X:0,7450981 Y:0,345098 Z:0,5137255 W:0,09803922}".

Other than that, the rest of the functions produce the right outputs.

# Answer
> 3 votes
Are your vector x/y values that you're passing to perm2d always integers? On the GPU that will interpolate, on the CPU you're truncating and always getting an exact value.

(This also doesn't look like Perlin noise.)

---
Tags: xna, c#, hlsl, terrain-rendering
---


title: XNA help - too much memory used?

text:
# Question
Title: XNA help - too much memory used?
I'm writing code in XNA 4.0, and part of my game entails drawing a textured grid of cubes. It is working, but the problem is the memory usage is growing way too rapidly. Each cube has 8 points, and each point is a VertexPositionTexture. A 16x9 grid takes 50MB memory, and that is just the grid and lines, no textures or anything else. Doubling the grid to 32x18 makes the memory jump to 150MB....I don't understand what is taking up so much room. I draw the grid using DrawUserIndexedPrimitives. The cubes can move around and be different sizes so I can't consolidate them to one set of vertices. What is the proper way to render a few thousand vertices without using so much memory?

These are all the members for my Cube class so far:

```
GraphicsDevice graphicsDevice; // for drawing this cube
Tileset tileset; // reference to parent object
VertexPositionTexture[] pointList; // the list of 8 vertices
BasicEffect basicEffect; // effect to draw using a shader
Vector3 localTranslation; // just 3 floats
VertexBuffer vertexBuffer; // for sending the vertices to the GPU

```

There are also a few functions that allocate memory for the pointList...but nothing out of the ordinary...

# Answer
Love all these minecraft inspired games! What an awesome project to get a kickstart into development. Glad you managed to track down the problem yourself as well!

---

Another optimization you might want to consider down the line: as many cubes form larger surfaces, instead of storing 100 cubes as a 10x10, store it as one big cube. This way you just need 8 vertices instead of 800. If one needs to be removed make a 9x10 block, then a row of 9 individual blocks (or even a 9x1 size block for bonus points). Remember just because something 'looks' like a million blocks, doesn't mean you need a million blocks. There is no such thing as cheating in computer science, only innovation.
> 1 votes

# Answer
There's a few things that come to my mind.

First of all, the SpriteBatch object is quite large. Is it nescessary to instantiate it for every cube?

The same could be said about the VertexBuffer. If the cubes are similar, you can re-use the vertex buffer.

As for the effect, again, if the cubes are similar, re-use it.
> 0 votes

---
Tags: xna
---


# Question
Title: Under what circumstances will a PIX 'Render' be different to the actual 'render'?
I am trying to implement dual-pass alpha sorting using Ogre material scripts, as part of my debugging attempts I want to compare two PIX captures, but when I attempt to debug a pixel in PIX, previously working 'geometry' is not displayed correctly.

My 'reference' blended geometry which works consistently, consists of a simple box with a translucent material, sitting over a set of opaque primitives. In my app this displays fine with the 'smoked' box tinting the objects/pixels behind it. When I load up my app starting through PIX this continues to work, but once I load a capture taken from this in PIX, it no longer blends the pixels and instead culls them.

I know it is PIX because in the debugger tab, I see the initial value of the pixel I am debugging is the correct blended colour, but the final frame buffer value is the darker incorrect colour - its as if PIX is 're-rendering' the shot and doing it wrong!

Could anyone suggest a reason for this behaviour?

# Answer
> 0 votes
If the reference rasterizer displays it correctly, then your code is correct and it is a bug in PIX.

---
Tags: directx, ogre, debugging, pix
---


title: Gameserver travel time checks

text:
# Question
Title: Gameserver travel time checks
I'm making a little RPG multiplayer game where each player can travel long distances. Traveling from point A to B can take up to 10 minutes and – once initiated – is an automatic process. Now, I am not quite sure how to go about this on the server-side, the server has to be the one telling the clients that the traveling player has arrived or not.

Do I have to run some sort of timer where I check every X seconds/milliseconds if all the traveling players have reached their destination in order to update the DB? (the characters are saved on the server to prevent cheating).

The way I imagined it was simply to capture the timestamp at the start of travel, then use the distance to calculate what the time should be when the player will arrive, and then run some sort of timer that checks each traveling players "start time" , "actual time" and "destination time", but since I have never done this before I'm not sure if this is a good way of doing it?

# Answer
You only need to update the database in two cases:

* the user performs an action or requests information from the server
* another player wants to interact with said user

Periodically checking if the database needs to be updated would put a lot of strain on your servers. Instead, information should be **updated only when it is needed**. In other words, you don't need to update the travel-status in the database from '*travelling*' to '*not-travelling*' unless a user requests that information or wants to perform an action that is affected by that information.

For example, let's assume that the player cannot do anything while traveling and that once he has arrived at his destination, he can be attacked by another player. Once the player starts moving, you could update the database with the following information:

* the user's position will be set to his final destination (even though he's not there yet)
* a travel timestamp will show when he'll get there

Let's now consider another user present at the same location. He's looking for someone to attack and will ask the server for a list of people in the area. The server will look for players who are both at that location AND have an expired timestamp.

If the second user decides to attack the first, or the first user logs in and requests his character data, before sending any information to the players check if any of them have an expired travel timestamp. If they do, update their records (maybe the player that did the traveling is tired and has a penalty applied to his attributes) and only then perform the actual action.

If you want your server to notify the users that they've reached their destination, do it the other way around: when the user logs in, tell them when traveling should end and start a timer on their machine. When the timer hits zero, make the client ask for an update from the server. Requesting character data should lead to the server noticing that the travel timestamp has expired and thus updating all of the data.
> 5 votes

---
Tags: server, timer, client
---


# Question
Title: How can I draw multiple lines connected via "nodes" with SlimDX?
I currently read out XML data with the following scheme: Position x,y,z

I try to add one new Vertex for each position node and add it to a Vertex array.

Then I try to render this list of vertices so I get all those lines connected to represent a "path" through space. (Space is 3D)

What I tried so far:

```
    [STAThread]
    static void Main()
    {
        var form = new RenderForm("SlimDX - MiniTri Direct3D9 Sample");
        var device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters()
        {
            BackBufferWidth = form.ClientSize.Width,
            BackBufferHeight = form.ClientSize.Height

        });
        form.Height = 900;
        form.Width = 900;

        LineVertex[] waypoints = new LineVertex[1024];

        XmlDocument paths = new XmlDocument();
        paths.Load("data.xml");
        XmlNode rootNode = paths.DocumentElement;

        int index = 0;
        foreach (XmlNode waypoint in rootNode)
        {
            foreach (XmlNode position in waypoint)
            {
                Console.WriteLine(position.ChildNodes[0].InnerText);
                float b = 1000.0f;
                float x, y, z;

                x = (float.Parse(position.ChildNodes[0].InnerText) / (b * b));
                y = (float.Parse(position.ChildNodes[1].InnerText) / (b * b);
                z = (float.Parse(position.ChildNodes[2].InnerText) / (b * b));

                Console.WriteLine(x.ToString() + " / " + y.ToString() + " / " + z.ToString());

                if (index % 2 > 0)
                    waypoints[index].Color = Color.Yellow.ToArgb();
                else
                    waypoints[index].Color = Color.Red.ToArgb();
                waypoints[index].Position = new Vector3(x, y, 0.0f);
            }
        }

        MessagePump.Run(form, () =>
        {
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.CornflowerBlue.ToArgb(), 0f, 1);
            // Since we don't have any lights in our scene, our lines won't receive
            // any light and will therefore be black...
            // ...but we want them golden as an asinus aureus, so let's disable lighting.
            device.SetRenderState(RenderState.Lighting, true);
            device.BeginScene();

            // Our struct was meant to describe a position and a color,
            // let's tell the device about it.
            device.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse;

            // In this particular case SlimDX does not need the
            // vertex stride, it will be automatically calculated.
            device.DrawUserPrimitives(PrimitiveType.LineList, 0, waypoints.Length / 2, waypoints);

            device.EndScene();
            device.Present();

        });

        foreach (var item in ObjectTable.Objects)
            item.Dispose();
    }
}

```

But this does not work, and I am sure it is the complete wrong approach!

EDIT: So far one solution worked out, but not very well. And I also need the Vertices to be changeable at runtime, so I locked at the documentation and samples, they always use VertexBuffer() to make it possible to dynamically change the Vertices by using a DataStream as Input for the VertexBuffer.

A question still open to me is, since I am used to "Update(Time time)" formats the procedural still of DX/OpenGL oftens confuses me. So I assume that MessagePump.Run() represents the drawing call that's repeated each frame. So if some values before the drawing call change like a Vertex, that's put into the datastream, I can instantly see the updated result on the screen. Is that assumption right?

# Answer
> 5 votes
It's been a while since I looked at SlimDX, so I feel like drawing some lines to remember how it feels :) Well, it looks like several colored lines are all we need, so lets arrange vertices as a list, describe it's order and draw it:

```
// Simple vertex with position and color.
public struct LineVertex
{
    public Vector3 Position;
    public int Color;
}

/* ...typical device initialization skipped here... */

var lines  = new LineVertex[100];
var random = new Random();

// Prepare line vertices.
// You will fill this array from XML instead of random generator.
// LineList will be used as a 3D primitive, so a line will be drawn
// between each pair of vertices, total of 50 lines in our case.
for (int i = 0; i < lines .Length; i++)
{
    lines[i] = new LineVertex();
    float x = (float)(random.NextDouble() * 2) - 1;
    float y = (float)(random.NextDouble() * 2) - 1;
    lines[i].Position = new Vector3(x, y, 0f);
    lines[i].Color = Color.Gold.ToArgb();
}

MessagePump.Run(form, () =>
{
    device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.CornflowerBlue.ToArgb(), 0f, 1);
    // Since we don't have any lights in our scene, our lines won't receive
    // any light and will therefore be black...
    // ...but we want them golden as an asinus aureus, so let's disable lighting.
    device.SetRenderState(RenderState.Lighting, false);
    device.BeginScene();

    // Our struct was meant to describe a position and a color,
    // let's tell the device about it.
    device.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse;

    // In this particular case SlimDX does not need the
    // vertex stride, it will be automatically calculated.
    device.DrawUserPrimitives(PrimitiveType.LineList, 0, lines.Length / 2, lines);

    device.EndScene();
    device.Present();
});

```

You may notice that these lines don't look very beautiful. Later in your development cycle you will probably want to replace them by lines made from triangles with a custom texture. By this point it may be easier to check out some nice book about DirectX rather than fighting it all by yourself.

EDIT: You wanted vertex buffers and interconnected lines? Actually, it would be a nice exercise to remember how this things work, so lets try and do it:

```
/* skipped device initialization */

var rnd = new Random();

// The maximum number of vertices we will ever have in a buffer,
// basically a buffer size limit.
const int maxVertexCount = 1024;
int lineVertexSize = Marshal.SizeOf(typeof(LineVertex));

// Create buffers once.
// You may notice Dynamic flag. This usage flag causes Direct3D to optimize for frequent lock operations.
// It's only useful when the buffer is locked frequently,
// otherwise a static vertex or index buffer should be used.
var vertexBuffer = new VertexBuffer(device, maxVertexCount * lineVertexSize,
    Usage.WriteOnly | Usage.Dynamic, VertexFormat.None, Pool.Default);

// Why such number of max indices? Read further :)
var indexBuffer = new IndexBuffer(device, sizeof(int) * maxVertexCount * 2 - 2,
    Usage.WriteOnly | Usage.Dynamic, Pool.Default, false);

MessagePump.Run(form, () =>
{
    device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.CornflowerBlue.ToArgb(), 0f, 1);
    device.SetRenderState(RenderState.Lighting, false);

    device.BeginScene();

    device.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse;

    // Simulate variable vertex count.
    int vertexCount = rnd.Next(1, 51) * 2;

    // Create a new vertex data each frame and setup vertices by changing their properties randomly.
    var vertexData = new LineVertex[vertexCount];
    for (int i = 0; i < vertexData.Length; i++)
    {
        float x = (float)(rnd.NextDouble() * 2) - 1;
        float y = (float)(rnd.NextDouble() * 2) - 1;
        vertexData[i].Position = new Vector3(x, y, 0f);
        vertexData[i].Color = (rnd.Next(2) == 0) ? Color.Gold.ToArgb() : Color.GreenYellow.ToArgb();
    }

    // Setup indices each frame in a special interconnected way:
    // the end point of the first line is the start point of the second line.
    var indices = new int[(vertexCount * 2) - 2];
    for (int i = 0; i < vertexCount - 1; i++)
    {
        indices[i * 2] = i;
        indices[(i * 2) + 1] = i + 1;
    }

    // Write generated vertices to the vertex buffer.
    // Lets receive a free performance improvement and use a
    // Discard flag since we aren't using old buffer data.
    // This flag tells Direct3D not to need to keep the old vertex or
    // index data in the buffer.
    var vertexStream = vertexBuffer.Lock(0, 0, LockFlags.Discard);
    vertexStream.WriteRange(vertexData);
    vertexBuffer.Unlock();

    // Write generated indices to the index buffer.
    var indexStream = indexBuffer.Lock(0, 0, LockFlags.Discard);
    indexStream.WriteRange(indices);
    indexBuffer.Unlock();

    device.SetStreamSource(0, vertexBuffer, 0, lineVertexSize);
    device.Indices = indexBuffer;
    device.DrawIndexedPrimitives(PrimitiveType.LineList, 0, 0, vertexCount, 0, indices.Length / 2);

    device.EndScene();

    device.Present();
});

```

# Answer
> 1 votes
There are a few things you are doing that you shouldn't. You also appear to have a type on or near the line where you call `WriteRange`, as there is an errant `}` in the code that will render it non-compilable. Similarly with the call to `DrawIndexedPrimitives` -- it makes it difficult to track down the actual cause of your problem. It would also help if you described the failure better than "it doesn't work."

That said, here are some things I noticed about your code:

1. You create an array of 1024 vertices, which you write into your vertex buffer using `WriteRange`. This is bad because it will attempt to write all 1024 elements of the array (it utilizes the array's `Length` property), and your buffer is only 60 bytes.
2. You hard-code the size of the vertex buffer, the primitive count, and the stride of the vertex. You should instead derive this information from the vertex type and the list of vertices itself.
3. You are using pre-transformed positions, which means your data must be in screen space coordinates already (-1 to 1 along the X and Y axis). If your vertices have positions outside that range, they are way outside of the visible area of the screen. You should not, in general, use pre-transformed coordinates unless you understand their implications (the transformation pipeline will not run).

This isn't related directly to your problem, but it's also not good to rely on the ability to iterate the object table and call Dispose on all it's members. That functionality will be going away in v2 of SlimDX and it just encourages sloppy reference handling.

---
Tags: c#, directx, .net, slimdx
---


# Question
Title: Perlin noise example the same on CPU as GPU?
I am looking for an example site with a Perlin Noise implementation in both CPU and GPU, that generates somewhat the same results in those two places.

I see many CPU implementations of Perlin Noise, but they don't match up with the GPU implementations that I found.

The reason I need this is for physics. The map is generated with Perlin Noise on the GPU in 2D, but this also means that to do physics, I must have a CPU version of the algorithm that generates the same results.

# Answer
> 7 votes
I don't know if the answer you are looking for exists, but personally I don't like the idea of independently generating values that you hope will end up identical.

I'm assuming that the map data is something you only generate once in the beginning of the scene. If so, much better to generate the data once, and use it twice. You should either generate the data on the CPU, and pass it to the GPU as a texture, or generate it on the GPU and write it to a texture, then give it back to the CPU.

---
Tags: physics, mathematics, hlsl, terrain-rendering
---


title: How to convert a Maya object to a VBO?

text:
# Question
Title: How to convert a Maya object to a VBO?
I'm currently trying to teach myself OpenGL... and quickly discovering that the Immediate Mode taught in old OpenGL tutorials is basically obsolete... which leads me to VBO's... which I kind of get but would like to start learning them in context.

What is the workflow involved in taking a 3D object from Maya or 3DS Max and converting it to something that can be turned into a VBO?

On that token, do these export workflows also deal with materials and textures, or is that handled in an entirely different manner?

# Answer
Saving it as a very simple text format or binary (wavefront obj is a common one) and then parsing it in the usual way. This is exactly the same as any other data parsing task. A vertex buffer object is essentially just an array of data that's held in video card memory. You'll probably want to read the data into system memory first and then convert it to a VBO. With that in mind, you might be best of starting with a simple shape (e.g. a cube) that you generate in code, convert that to a VBO and then try loading files. This ensures that you're working on one problem at a time. So, get the spinning cube running first (That's the 3D graphics programmers 'hello world') and then worry about importing meshes from other sources.
> 2 votes

# Answer
From 3d application you have to export the data to any format that you can parse. VBO are storage to hold vertex, index... information. In your program you have to parse back the information and feed it into the VBO, so OpenGL can draw them.
> 0 votes

---
Tags: opengl, maya, vbo
---


title: What are Textures in games development?

text:
# Question
Title: What are Textures in games development?
At any time, a game will likely have many objects rendering textures.
So what is a texture? an image for example?

# Answer
Yes, a texture for most purposes is an image.

Once a texture is loaded from a file, it can be applied as a sort of "decal" to any polygon you wish.

When you see textures in an image file they typically appear a bit warped,

That's because when the texture is "wrapped" around the model, it will all even out and wrap around the model properly. You use a technique called UV mapping to be able to create a nice texture that will wrap around the model properly.
> 13 votes

# Answer
Yes, it typically is an image (often of a pattern) applied to the surface of a 2D or 3D model.
> 4 votes

# Answer
Textures are basically images that are used in 3D games on 3D objects, 2D planes in 3D space, or GUI elements.

Textures can also be generated at real time.
> 2 votes

---
Tags: textures
---


# Question
Title: Turning model from 3ds max file into sprite
I'm planning to buy animated 3D assets to render and use as 2D sprites in my game, but i don't know anything about 3ds max or own any software. How do i render the animations (i need top-down ones) to turn them into a bunch of pngs?

From there i already know how to create a spritesheet.

I assume there is a more streamlined way of doing this than opening each file in the 3D software, looking at each animation frame, and capturing the screen?

# Answer
Get Sprite Forge (http://www.d-grafix.com/?page=spriteforge). It can automatically render out a full sprite sheet of your model (including animations) with incremental camera angles. A bit old, but I haven't regretted spending the money on it.
> 2 votes

# Answer
Max (and most other modellers) also have rendering support, so they can render your scenes out to images -- you don't need to capture the screen to get your models into an image.

The process of creating sprites from a model is essentially invoking the modeller's renderer with the desired settings (for lighting, anti-aliasing, and what have you) repeatedly at every desired camera angle. The settings you have to select really will depend on the desired effect you want in your sprite images -- you'll have to experiment.

Most serious modelling tools have scripting support, so you can create scripts to automatically render the scene from all the desired camera angles and possibly even stitch the resulting images together in a sprite sheet. Here's one of many available scripts for Max, for example.

Since Max is quite expensive and you don't currently own it, you probably don't want to drop the cash on it. You can use Blender, which is free and has Python scripting support that should allow you to build an automated workflow for your sprite rendering. Just make sure the assets you purchase are loadable by Blender -- try to get a sample file from the author first and make sure everything works well (this is a good idea even if you don't use Blender, note).
> 3 votes

---
Tags: 3d, sprites, models, 3dsmax
---


# Question
Title: Component System - Editor Data Management
I'm trying to construct an editor in C# that exposes game components to IronPython, so it may create the game object definitions to be used within the editor:

* C# Exposes the components to the python script (Spatial, Movement, SpriteView, etc.)
* IronPython creates the game object definitions (or templates) by attaching components to a game object.

At the startup of the editor:

1. The Python script is loaded with all of the game object definitions.
2. Tools are updated with the new objects (availability for painting).

The problem I'm having lies when I'm saving and opening the editor data:

1. When saving, I use C# to serialize all of the constructed game objects (including the game object definitions generated from python) to a file.
2. When opening, I use C# to deserialize the data. - Since the Python script is not synchronized with the serialized components, I will run into a big problem when I change anything in the script.

One solution I had was to only serialize the definition name of a game object, therefore when I deserialize my data I will have to do a lookup for the target definition (created by the script) and simply clone it. But, it still will not be entirely in sync with the editor data (some data will be changed on each game object like for example the position (note when I say game object I do not mean the definition)).

Another solution might be to use a database and save out all of my editor data to it (perhaps using the entity database in C#). I'm not entirely sure if this will solve my problem.

Any help would be appreciated, thanks!

# Answer
I decided to go with the database for my objects.
> -1 votes

---
Tags: c#, editors, databases
---


# Question
Title: What are the technologies used to create Metal Gear game?
What are the technologies (programming languages and engines for example) used to create "Metal Gear : Snake Eater" and "Metal Gear : Guns of The Patriots"?

Is it usual to keep those things secret?

# Answer
For Metal Gear : Guns of The Patriots, Kojima used their own in-house engine. Its unavailable to general public. C++ is the de-facto of the console game industry. So, I believe it was in this case too.

Recently they are developing a new engine which they have revealed E3 of this year, named Fox Engine. They say they will be using this multi-platform engine for their future titles.
> 5 votes

# Answer
Each time I see a new Final Fantasy or a MGS game I ask myself the same question. It's obviously the same models, animations, shaders, particle systems and whatnot, but in the hands of certain developers they feel like something out of this world.

I'm quite sure it's was not the bare technologies that made those games, but an amazing art itself, design direction and overall producing. You may find:

As you can find out by following the links above, it's nothing totally special or absolutely unknown, but MGS staff turned usual high-tech into a great experience by a burning intent to make an amazing game, also by pouring millions into their art and coding departments :)
> 2 votes

---
Tags: software-engineering
---


title: To scene graph or not to scene graph?

text:
# Question
Title: To scene graph or not to scene graph?
I've been struggling with a decision regarding whether or not to implement a scene graph in my game. I have some use cases that call for such a tool, but I haven't been able to get through some of the implementation details.

Some background: I'm writing a space shooter type game targeted at mobile platform (Android, primarily) and my code is almost entirely C++. I'm not using any middleware; the rendering and physics engines in particular are my own creations. My physics engine updates locations of objects based on forces and impulses. I have no animation system as of yet but may visit this at some point (which may or may not have anything to do with this discussion).

First, I'll describe a good use case. I would like to have a boss that is made up of several discrete parts, each of which can be damaged / destroyed independently. For example, I might have a boss that has an arm that can receive damage independently of the rest of the boss entity. When the arm is destroyed, a fire particle effect located at the bosses' shoulder could indicate that the arm is now destroyed.

As it is, I have decided to try solving such problems with constraints in my physics engine to keep such compound objects together. One such constraint provides 0 degrees of freedom and is essentially a transformation matrix. This is really an attempt to circumvent a problem that ultimately turned me off of scene graphs in the first place, described below.

The primary reason I turned away from use of a scene graph is because I could not find an efficient way to keep nested objects (objects that inherit a transformation from their parent) in both the physics world and the rendering scene. The physics world needs objects to be in world-space (or at least the same space) while the rendering scene needs objects in parent-space. Tracking locations in both spaces might help (and be inevitable) but raises its own concerns, not the least of which relates to performance.

However, given use cases like the one described above, I think that being able to 'work' in parent space will become very important, and trying to force my physics engine to maintain these relationships through the use of constraints is going to become problematic.

Given the use case and predicament described above, should I use a graph structure to pass transformations from one object to another? If so, how should my physics engine calculate new locations and perform intersection tests for objects in different spaces?

# Answer
> 11 votes
Have you actually tried a hierarchical graph and **measured the performance?**

Have you investigated simple physics engines to see how they handle the problem, even a 2D engine that has linkage between objects would help guide you in a proven direction.

I would not try to run your physics in multiple spaces, the complexity would be daunting. Run the physics in world space and add functionality to create transforms of your hierarchy to move local space objects out to world space and back. Your constraints, of necessity, must be in local space relative to the parent object.

As a side note even a pure array of objects is a "scene graph," just a very simple one. Don't be afraid to organize data in ways to solve problems and especially don't decide that performance of that data organization is a factor without even having measured that performance.

---
Tags: scene-graph, graph, architecture
---


# Question
Title: Why is OpenGL provided with latest GeForce drivers so extremely slow?
I'm writting a code in OpenGL and using two computers - an old and a new one.

On the old computer (which I use for debugging/creating implementation for the old GL) I have GeForce 5500 FX. Before windows reinstall on it, I had NVIDIA drivers with OpenGL 1.5. And everything worked perfectly. Games made quite good FPS, even with dozens or hundreds sprites.

However, after XP reinstall, I installed the drivers provided with my video card but it seems there's no OpenGL at all (mysterious 'GDI Generic' renderer). So I tried to download the newest NVidia drivers. After their installation I saw there's **OpenGL 2.3** but when I runned my app it worked with **extremely low FPS** (about 0.25, I mean I had to wait four seconds for any app reaction) with only one sprite. And as I loaded smaller images, the FPS relatively increased, but on the new computer it's always (no matter how big and how many sprites) speed, so it must be the perfomance problem. Without any sprites, it seemed it worked normal, but game without graphics doesn't make any sense.

That's why I downloaded the oldest drivers for NVIDIA GeForce 5500 FX I found on the Nvidia site. But they're still providing OpenGL \> 2.0 (2.1 exactly). The problem's the same.

I also tried to change all the properties of OpenGL to increase performance but it didn't help too.

So what can I do? **I'd like to find drivers with OpenGL 1.5** but it seems they're not on the NVIDIA site and most people say it's the best to download they from there.

# Answer
> 5 votes
The problem is most likely that you're using non-power-of-two textures. The drivers for the GeForce FX series support these texture sizes, but will force your program to run in software mode. If this is the case then you'll need to use power-of-2 texture sizes (2, 4, 8, 16, 32, 64, etc) instead.

# Answer
> 4 votes
It sounds like the 2nd machine is doing software rendering - hence the slow frame rate.

I'd check that the new version of OpenGL is detecting the card properly. It could be that it thinks that it doesn't support OpenGL fully - or at least the bits you are using - hence the fall back to software.

Do other applications that use OpenGL work OK?

If it's just your program it could be the way you are initialising OpenGL. I'd post a question on Stack Overflow - with the code.

# Answer
> 1 votes
Nvidia have an entire archive of all their older driver versions that you can find at their Windows XP/2000 Driver Archive

Specifically this version (71.84) Claims to have OpenGL v1.5 so if you want to give it a shot with an older version to see if that truly is the problem then there is nothing actually stopping you.

---
Tags: opengl
---


# Question
Title: Are C and Objective-C sufficient for creating games on the iOS?
These days, I'm focusing on games development on the iOS.
C++ is the lingua franca for games development but seriously, I prefer to code in C programming language, not in C++.

So for iOS games development, are C and Objective-C sufficient for creating games?

# Answer
the only real restriction you have while developing for iphone is the sdk apple released for iphone. other than that you will mainly use OpenGL and OpenAL which are both pure C code. in some cases you might want to use some c++ libraries (like box2d) but there are equivalents both in C and Obj-C.

so every game you release for iphone should at least have some obj-c codes to load your application and to do some basic file read/write things, other than that you are free to use pure C, Obj-C or C++ or even a combination of those languages.

also as jasconius said there are many games written and published using only Obj-C. there is even a opensource gameengine named cocos2d-iphone out there that powered many iOS games so far.
> 5 votes

# Answer
Yes. There are numerous iOS games made with only these languages. C++ is optional if you absolutely need it.
> 3 votes

---
Tags: c++, software-engineering, objective-c, c
---


# Question
Title: How can I generate a terrain heightmap from the perlin algorithm?
How can I generate a terrain heightmap from the perlin algorithm? I am trying to make a terrain generator (like World Machine). This is the source code I have for the perlin. The only thing that I can't figure out is how to use the perlin algorithm to generate a heightmap image.

# Answer
A terrain heightmap texture is a regular grid of point samples, which indicate the height at that particular location on the terrain. When you want to create such a heightmap from a function `f(vec2)`, you evaluate the function with the position of each of the grid points of the terrain to get the value at those points, and let that be the color value in the texture.

If the function expects the coordinate in a different space (other scale, offset, range) than the pixel coordinates of your texture, you need to map the pixel coordinates into the coordinate range you wish to invoke the function with.

The output values might have the wrong scale or offset, so you might need to compensate for those by offsetting and scaling the returned value to fit inside the range of values your texture component expects (0 through 255 for a typical 8-bit component):

```
foreach (y in [0..height))
  foreach (x in [0..width))
    vec2 p = transform_pixel_position_to_parameter(x, y);
    tex(x,y) = height_offset + height_scale * f(p);

```
> 3 votes

# Answer
Your answer might lie in making additive multiple passes:

Pass 1: Make a 2D array storing values from the perlin generator. The bigger the array the more detail.

Then scale this array to your maximum/minimum height values for terrain.

Pass 2 through N: Offset values of array by further perlin generations, with each pass carrying a smaller weight. This should allow for further detail, taking away from the 'smoothness' of a single pass.

---

Now the world making suite you mentioned seems (at a glance) to support things like natural water formations/erosion over time. These can be a bit more complicated to replicate simply, but the general idea is:

Water can only lower/smooth out land, so in any place water must rest, find the deepest point, then create a quadratic gradient outwards (where higher polynomials represent further complexity, drop offs, that sort of thing).

Flora and other plant life can easily be added using rules like: Plant A can only exist a certain distance from water, and only on a circular area with an average height differential between each point less than a certain amount.

That should make for some nifty looking terrain on the cheap (processor wise).
> 0 votes

# Answer
Wikipedia about Perlin noise:

> The function has a pseudo-random appearance, yet all of its visual details are the same size (see image).

Landscapes have much more varying detail size than Perlin noise, wich is why a single 2D noise used as a heightmap looks unrealistically smooth. You can add additional layers of noise to improve this; a layer with low noise scale also should have a low weight on the overall result height. You can use irregular fractions for the scale to avoid repetitions.

World Machine seems to have a lot of additional features that don't seem to directly rely on only noise, like the valleys perpendicular to the mountains, that may be difficult or impossible to replicate this way.
Perlin noise is also relatively smooth, no matter how many layers you add onto each other, so it can't produce a mountain ridge without running an additional function on the output.
> -1 votes

---
Tags: algorithm, terrain-rendering, terrain
---


# Question
Title: Quadtree terrain splitting - I don't get it
Most of the papers i've read base their terrain in some form or another on a quadtree. See this at **page 38**:

http://www.slideshare.net/repii/terrain-rendering-in-frostbite-using-procedural-shader-splatting-presentation?from=ss\_embed

Doesn't the first point contradict the bottom two? How can you have a fixed 33x33 vertex grid per leaf yet talk about adaptive division in a quad tree? The terminology is confusing and i'd appreciate any clarity on this!

---

Here are my assumptions:
*Re-placing the patches everytime the quadtree changes would be a hit wouldn't it?*

1. Quadtree starting at terrain bounds.
2. Iterate down to observer location.
3. Constrained version (no more than 1 level difference between neighbours)
4. Frustum cull.
5. Place terrain patch in each resulting leaf, where the scale differs but the resolution is always 33x33.

# Answer
No, not really. If you are thinking of using a quadtree for terrain level-of-detail, the nodes you store will all usually possess the same data structure.

In your example, that structure is a 33×33 submesh that the nodes will hold. Depending on the level of the node, that 33×33 mesh will adapt (adaptive) to cover a wider area. The larger node will fill a larger space, but its submesh is still a 33×33 vertex patch.

After the tree is built you can do your frustum culling by going down the tree and discarding the nodes that don't intersect.

One thing to keep in mind, is that you will very likely need to address the cracks that come up when a larger node draws next to a smaller node. One easy way is to simply adjust (collapse) any unshared vertices between the meshes.

As for you other question about the tree being replaced, yes. Unless you want to get into data managing the tree, I suggest just making a stack and flush it out when the view moves sufficiently.
> 6 votes

# Answer
The "unit" of terrain are 33x33 blocks. If you are close, that is what you will see. If you are further away, these blocks are fused into lower LOD chunks.

The reason they use fixed chunks at the lowest level (leaf), is because modern hardware is a lot faster with static geometry. Systems like ROAM, where a lot of work is performed to reduce eventual polygon count, incur into sizable performance penalties.
> 3 votes

---
Tags: terrain-rendering, terrain
---


title: Setting up OpenGL 3.3 in SDL 1.2

text:
# Question
Title: Setting up OpenGL 3.3 in SDL 1.2
I've been using SDL 1.2.14 for awhile without using many of the features from newer OpenGL versions. I'm now interested working only with the 3.3 API (not using the deprecated functions, etc... that's the latest my graphics card supports), but I'm having trouble getting set up.

Here's some information about my development environment:

* Windows 7 64 bit
* Eclipse Helios CDT
* Mingw Toolchain
* C++

I've tried building SDL 1.3 and following this tutorial. This ended up being a pretty big pain and I gave up amid a stream of compile errors - I'd prefer to not go this route if possible. I know also that GLEW/GLEE or some do-it-yourself extension function pointers will be required.

So basically: is it possible? If so, what is the best/easiest way to make it happen? Thanks!

# Answer
> 8 votes
Only SDL version 1.3 provides support for creating an OpenGL 3.3 **core** context. So you should upgrade. And if you're having a problem upgrading, that's something you need to get worked out.

However, if you want to use a 3.3 **compatibility** context, all you need is recent drivers. Well, that and 3.3-capable hardware (anything advertised as DX10. Except from Intel).

---
Tags: c++, opengl, sdl, mingw, eclipse
---


# Question
Title: Preventing XNA from anti-aliasing textures?
It appears that if a image is undersized for covering the model it's set to cover, it anti-aliases instead of stretches. How can I control this behavior?

# Answer
> 5 votes
You should set the sampler state to Point:

```
graphicsDevice.SamplerStates[0] = SamplerState.PointClamp;

```

# Answer
> 3 votes
The default texture magnification filter seems to be bilinear filtering, which will interpolate linearly between texels if the texture needs to be blown up to cover the target. If the sample doesn't lie on a texel center, bilinear filtering takes the closest pixels horizontally and vertically and blends them together based on their distance to the sample point.

If you want a *square pixel* look you probably want the Point (or Nearest in other APIs) filter, which instead picks the closest texel to the sample coordinates and uses the value of that texel alone.

---
Tags: xna, textures, antialiasing
---


# Question
Title: How difficult and expensive would be to obtain 3D models for my game?
So, basically I'm looking for a way to get some 3D models and animations for my game.

I know this is kind of vague, but I don't need a precise answer, the details would be like this:

* The 3D models are for humanoid units, but there could be some alien-ish units too.
* The level of detail of the units would be similar to Warcraft III ones
* Amount of units, to begin with, 30-35
* The units will need to have animations like: walk, attack, block and attack, and maybe some special movement.

That's all.

Now, the question is, how hard/expensive/complicated would be to get those units made by an artist, bought in a website, etc.

I just want to know what to expect.

Thanks!

# Answer
Colleague of mine was looking for a freelance 3d-artists lately, I've got to participate a bit. From what I gathered, there are a lot of nuances strictly defining the final price, but basically, it's all stands on time-per-feature basis. I will briefly describe a process from a layman's point of view, corrections are welcome. Also prices in this post are based on Russian market, I suspect prices in Europe or USA will be lower due to much bigger amount of good artists and resulting competition.

**Base model**

So lets say you have your concept art and now you need a low poly models based off it with textures and animations. Let's talk about model itself. Most time-consuming part is going to be an optimization of initial high-poly model to make it low-poly while preserving distinct features. (3d-artist will make a high-poly model from you concept art first, even if you need a low-poly), and then a lot of time will be spent by preparing the model for animation by optimizing vertex grid so it won't make weird bumps and spikes when animated. Lastly it's going to be unwrapped for future texturing, and that's it.

If you stop here, you will receive a model ready for texturing and animating. Depending on complexity of the concept and skill of the 3d-artist, this will take 1-4 days of pure work time, and you best be sure to avoid changes like: "I wanted this alien creature to have two legs, but now I changed my mind and it needs a third leg ASAP". Here in Russia an unskilled student can make you this kind of model for $40, and a professional would ask for about $250.

**Texturing**

Actual texturing and animating of prepared model is a different story. Price for texturing depends on the concept art. If it's of very high quality, and modeller is strictly required to keep the style of art intact, it's going to be expensive. All in all a professional guy would take another $150 for diffuse, normal and color specular textures. Don't economize here, quality textures can make bad models look good.

So all in all, I would say that a price of a high-quality low-poly model is about $400-500 here. Just an example, see this gal ? She also has two another heads, 4 sets of armor and civilian clothes, it all took about 19 work days and a total cost was $2500.

**Animations**

You may notice that price is climbing high already, and we still have animations to cover. What can I say, it's beyond expensive. Unskilled animator may ask for about $80 per 1 minute of low-poly animation, but it will be crappy as hell. Professional guys will ask for about $50 per second (or ~$20 per second if you're fine with sloppy moments).

Bad animations can kill the game pretty easily, so the usual solution here is for small developers to ask large companies like Akella to use their mo-cap equipment, they're often generous and charge about $330 per 15 minutes of mo-cap.

Sorry for a long post,especially since you need to take it with a grain of salt: actual result is all about diplomacy, bargaining and business approach. Who knows, maybe you will even find a real team member who will do it all for free hoping for a large profit share.

*Little footnotes:*

* You don't have a concept art? You're doing it wrong, you need to find a lead artist so your game won't look like a mix of jigsaw puzzles assembled together.
* Buying models from "art markets" is much cheaper, but often unacceptable due to difference from art direction. If you can use them, do so by all means.
* If you're making a FPS, scale all prices by a magnitude of 4 :)
* If you're doing all this steps with a single modeller, then ask for a discount.
* If you're doing a lot of characters, scale all prices by a magnitude of 0.75 :)
> 7 votes

# Answer
A couple of resources for you to check out...

My experience has been that the quality of models can vary widely, and often the 3D models that are free are often of low quality, or ironically of such a high level of detail that they aren't useable in a game environment (too many polys).
> 2 votes

# Answer
I can't provide a useful answer for how much time or money it would cost to pay a professional to make these models, but I can say that it would be a small fraction of the cost to buy them pre-made on a website like turbosquid. You will almost certainly not get exactly what you want this way, but the time and money investment will be much less. I would suggest you start shopping around for off-the-shelf models to get a feel for whether that will work for you and how much it will cost.
> 0 votes

---
Tags: 3d, models, art, costs
---


# Question
Title: How to get started with Unreal Engine for iPhone?
OK i have decent amount of knowledge of C++. I want to make cool games for iPhone using unreal engine and I have access to UDN. But everything seems cluttered on UDN. I have downloaded source from there. It would be great if someone can provide information about How to get started and list of resources. Thanks!

# Answer
You can start of with any tutorials you like(even non-Mobile). First your goal should be getting used to with development environment. If you want to deploy you game to iOS devices then, you just have to follow constrain of that device.
> 3 votes

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


# Question
Title: Tailoring sound volume for different speakers
Different sound effects are played differently across different speakers. For example, when I use my laptop speakers, sounds are notably softer and low pitch sounds often become inaudible unless I turn my volume up from 20% to 80%. Yet if I try to increase the sound's amplitude, when I plug in my Creative T10 speakers, everything sounds too loud.

My problem is that I cannot increase sound uniformly across the board just to make the soft sounds more audible on a laptop, since as mentioned, everything sounds perfectly balanced on good speakers, it's just bad speakers (laptops) that ruin things.

What options do I have to ensure the volume is consistent across different speaker configurations?

PS: I'm using Flash, so there's no way to check hardware.

# Answer
The problem here seems to be that certain speakers just aren't very good, I'm not sure if there's a solution, since there's no way to check if the user has a set of $1,000 5.1 surround sound speakers plugged in, or is using headphones, or if they're using the generally crappy built in speakers on a laptop. This is actually a problem for pretty much anyone, since even if you could check their hardware configuration, the user might have their hardware configuration set up wrong, or they might occasionally switch out their 5.1 speaker system for a pair of crappy headphones because it's 1am and they don't want people calling the police for noise complaints (or they don't want to wake their roommates/parents/etc).

So, the best solution would be to make sure your sounds sound good on a decent pair of speakers, and they all have an equal volume between themselves. Basically, no sound is ear drum breakingly loud, or whisper quiet when compared to the other sounds. If your game has speech, then include subtitles so users can play with the sound turned low, or muted entirely. Include volume controls so users can set the volume themselves (including a mute button because that 30 second music loop is starting to get annoying).

In short, you can't control if someone has bad speakers, so don't worry too much about it. If sound is vital to your game, then include a note at the start saying so.

**Sidenote**: there's probably some fun stuff you can do in audio editing programs to fix some the issues with lower or higher pitched sounds, but all speakers have a maximum and minimum frequency range, and there's very little you can do to check that, even if you were making a native game (except for mobile development, where you know the range in advance)
> 5 votes

# Answer
**Short answer**

Give the user a volume control and allow them to adjust it to their preferences.

**Long answer**

There are so many variables out of your control in this problem that you won't be able to solve it. It's not just the speakers, it's how they are setup, what the ambient noise is in the room, and even the user's hearing ability (or lack of).
> 4 votes

---
Tags: flash, sound, sound-effects
---


# Question
Title: How do you structure a 2D level format with collisions etc. in Java (Slick 2D)?
I am developing a game in Java. 2D Fighter, Kind of like the 2d flash game Raze(http://armorgames.com/play/5395/raze). I currently am using the Slick 2D game library and am researching how to structure my levels. I am currently stuck on the problem of the level format(e.g. file format). How do you structure a 2d level with collisions etc.?

Level Notes: Will go up down left right

**NOTE: New to gamedev**

# Answer
> 1 votes
There are many ways of structuring 2D levels.

One way would be to create a Level class which contains all the GameObjects and their physics-related information. It would know of where each GameObject and its rotation, along with each GameObjects physics bounding shape its orientation. Then, you could create an editor for the Levels and let it save/load Levels using serialization or some other method.

The file format doesn't really matter, as long as it suits your needs. If you don't need to be able to edit it from outside an editor, you could just use serialization. If you do, then you can use a text file that describes all of the GameObjects that your Level contains. For example, your file format could be like this:

```
<Level name="Tutorial">
    <GameObject name="Floor1">
        <Physics type="static" shape="Box(1000, 10)"/>
        <Orientation position="0, 800" rotation="0"/>
    </GameObject>
    <GameObject name="Bob the Unicorn" class="com.stackexchange.game.Unicorn">
        <Physics type="dynamic" shape="Polygon({10, 20},{40, 30},{-10, 500})" mass="99"/>
        <Orientation position="50, 30" rotation="50"/>
    </GameObject>
    ...
</Level>

```

# Answer
> 1 votes
Check out the Tiled Map Editor. It's a fairly flexible and user-friendly program, and Slick natively supports its file format, which makes it very easy to use.

You will want to have at least two layers in your map: one with the map graphics, and one collision layer (which won't be displayed in the game). When the player tries to move into a new tile, check the collision layer to see if a tile exists there, and if so, block the player from moving into the tile.

If you want to use arbitrary terrain shapes, you'll have to use something more like skyuzo suggested. Tile maps are less flexible, but they can still allow for a large variety of levels, and they're easier to work with as a beginner.

---
Tags: 2d, java, level-design, file-format, slick
---