# Question
Title: Understanding the perspective projection matrix in OpenGL
Setting the **Perspective projection matrix** in Open GL (including OpenGL ES 2.0) has the following general format:

```
glm::mat4 perspective(float fovy, float aspect, float zNear, float zFar);

```

Notice the **last two parameters**; First one specifies **zNear** plane, which is the plane closer to the camera. The second one specifies **zFar** plane which is far from the camera.

It is common knowledge that, in OpenGL, things that are further, in other words "deeper into the screen", have **negative Z axis**. Why then all the OpenGL examples, that set perspective projection matrix (taken from reliable sources like **OpenGL SuperBible** and simmilar) look like the two above mentioned parameters (zNear, zFar) of Perspective projection funcion are swapped?

*This example is taken from GLM(OpenGL Math) webiste:*

```
glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);

```

You can see, that the zNear parameter is actually further from the camera, than zFar parameter, which is 100 points closer to the camera/viewer.

Can you provide **easy to understand explanation**, please? I it is not just one but all the examples, which pass zFar as higher positive value than zNear. Thanks.

---

## My Example:

In my code, when I set:

```
glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 1000.0f, -500.0f);

```

I assume my frustum being **1000 points long in z-positive** direction and **500 points long in z-negative** direction.

When I set things like this, I can see at least some object, although things are not perfect: for some reasons I see only objects positioned on negative z coordinates.

This might relate to my incorrect understanding of the perspective projection function.

# Answer
The method in question (`glm::perspective`) and its ilk are essentially wrappers or re-implementations of gluPerspective. As you can see from the documentation of that function, the near/far values are distances from the view plane, and are always positive.
> 7 votes

---
Tags: opengl, 3d, linear-algebra
---


# Question
Title: Does it makes sense to apply perspective projection, in a 2D game?
Does it makes sense to apply perspective projection, in a 2D game? What will be the cost for doing so, and does it overweigh the benefits gained from the 3rd dimension?

---

Perspective projection has features that could be used in 2D games. Two very beneficial characteristics that come to my mind are:

1. Using perspective projection as a substitute for parallax scrolling.
2. Using perspective projection to perform depth order for 2D sprites

On the other hand, perspective projection resizes objects with distance, including 2D sprites. That is why mip mapping has been developed. Mip mapping, however, does not always produce perfect results, as it relies on interpolation between two neighboring mip-mapped frames. This might not be sufficient, for a 2D game, where developers require pixel-based precision and detail.

# Answer
It's not really a huge win in general.

You can use a perspective projection into a true 3D scene to get an effect like parallax scrolling background layers from classic 2D games, sure. But it's not really an easier to implement that than it is to implement scrolling layers.

You don't get any benefits with respect to depth ordering -- you'd still need to give each sprite an appropriate depth (Z coordinate) and this is no different in practice than assigning the sprite a depth layer. You get slightly smoother transitions between depth layers because they aren't discrete layers, but that's about it. You can use the depth buffer and test to get properly rendered sprites regardless of whether or not you use a perspective (versus orthographic) transform -- and either way that's a wash since you generally have to manually sort sprites back-to-front for rendering any that have alpha. You actually get that basically for free with a regular background layer index.

You can counter the resizing by pre-scaling the sprites based on depth, typically in a shader. This avoids the need to try to rely on mip-mapping to fix up the appearance (mip-mapping is a bit of a red herring here, as it only improves the visual quality of the resulting textured quad and does not fix the fundamental resizing problem and it's not why it was developed). On the other hand, you may find this scaling desirable if you're going for an obvious "2D in 3D" look, like Shadow Complex, versus an obvious 2D look like Super Mario World.

In short, like all things, *it depends*. If your game is meant to be a 3D game constrained to a 2D field of play, it makes sense. If it's not, and you don't need any of the small benefits (such as smooth layer transitions), it's probably not worth doing just because exactly equivalent results can be obtained with less work in another fashion.

If, on the other hand, your frameworks and toolchains are only set up for a perspective projection and cannot be changed or swapped out, and you are only doing a simple 2D game, you can certainly make it work. There's no clear answer to this and the differences between options are pretty minor.

Go with the option that involves the least work.
> 6 votes

# Answer
I am currently developing a sprite-based 2D game where we are using perspective projection instead of orthogonal one. Obvious reason for using perspective projection was that we wanted to have multiple layers with parallax scrolling and we didn't want to adjust properties for each layer (movement speed, scale) manually.

Using perspective projection in 2D game does not mean that you cannot render 2D images with full quality. We have defined a plane (Z=0) in which one texel from texture equals exactly one pixel on screen, and basically all elements that are relevant to game logic are places on this plane. Placing elements on other planes will scale the sprites as you would except. Also, note that using perspective projection does not deform sprites if they are facing the camera (as they should be). That is, a square sprite on plane Z=0 is a aquare also on any other plane (at least when you set up the projection properly; I'm not 100% sure if you can set up a projection that deforms sprites).

Pros:

* You get layers and parallax scrolling for free
* You can add 3D objects to your scene so that they appear realistic (regarding to perspection)

Cons:

* More mathematics involved (you have to calculate plane where one texel equals one pixel)

And now, the most important thing: should you use it? Well, it's up to you. I'm very happy with our solution and it is really helping us to achieve the effect we want. On the other hand, if you simply want to draw some sprites and maybe a one background layer, then there might be too much overhead for using perspective projection instead of orthogonal one.
> 2 votes

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


# Question
Title: Generating random values, keep trying till value within bounds are generated
Sorry for the strange topic name, couldn´t think of a good way to describe it. I´m basically trying to achieve the following:

I'm placing items randomly on the screen, but these items shouldn't be placed near eachother at a given distance. This is the process I have in my head right now:

* generate a random location
* check if this location is not near any other objects
* it is near -\> start the process over to generate a new item (till it is not near anymore)

I've run into this scenario multiple times but could never think of a way to efficiently do this, while I do feel that there is a simple way to do it. Here is the implementation I have right now. I feel like I should use a while loop but I can't get my around how to do it. The code is in AS3 but that shouldn't matter.

```
public function generatePlanetsFromXML(xml:XML):void
    {
        planets = new Array();

        for (var i:int = 0; i < xml.projects.project.length(); i++) {

            var planet:Planet = new Planet();
            planet.data = xml.projects.project[i];
            planet.radius = (Math.random() * 20) + 20;
            addChild(planet);
            addObject(planet);

            planets.push(planet);

            calculatePlanetLocation(planet, i);
        }

    }

    private function calculatePlanetLocation(planet:Planet, i:int):void
    {
        var randomX:int = (Math.random() * (worldwidth - planet.width)) + 20;
        var randomY:int = (Math.random() * (worldheight - planet.height)) + 20;

            //get a location that isn't close to another planet
            //keep looping till the distance is higher than minimum distance
            for (var j:int = 0; j < planets.length; j++) {

                if (i != j) {

                    var dx:int = planets[j].x - randomX;
                    var dy:int = planets[j].y - randomY;
                    var distance:int = Math.sqrt((dx * dx) + (dy * dy));

                    if (distance < minPlanetDistance) {

                        trace("retry getting location..");
                        planet.alpha = 0.3;
                        calculatePlanetLocation(planet, i);

                    }else {

                        //distance is fine, planet can be placed!
                        planet.x = randomX;
                        planet.y = randomY;
                    }

                }else if (i == 0) {

                    //first planet should always be placed
                    planet.x = randomX;
                    planet.y = randomY;
                }

            }
    }

```

# Answer
> 8 votes
As you can probably imagine, the biggest problem with that approach is that you don't have any idea how long it's going to take to populate the world. If you're unlucky, the random number generator can make you do several times the amount of calculations than you would need to do given a strict iterative approach.

One way you could work around it in this situation is by using a grid. Maintain a list of all the valid grid coords to place a world at, and every time you place a new world you remove the coords that are no longer valid from this master list. That way you only have to pick a random spot once since all spots you are picking from are valid.

Basically, the algorithm would look something like this (in really rough pseudo code):

```
int[] validGridCoords = AllGridCoords();

function PopulateUniverse()
    for( 0..NumPlanetsRequired )
        if ( validGridCoords.Count < 1 )
          break for loop;
        var CoordToPlaceAt = validGridCoords.RandomElement();
        SpawnPlanetAt( CoordToPlaceAt );

function SpawnPlanetAt( int coordToSpawnAt )
    // initialize planet
    var planet = new Planet( coordToSpawnAt );
    foreach( var gridCoord in validGridCoords )
        if( gridCoord is close to new planet )  // you could use Manhattan distance here
            validGridCoords.Remove( gridCoord )

```

**Update**: as NeilG rightly is alluding to in the comments, this naive solution has a few problems. For one, if your "is close" number is relatively small (i.e. around the radius of your largest allowed planet) or proportional to the radius of the planet, you can run into situations where you place a "large" planet on the edge of the valid areas and it might reach far enough into the prepopulated area to either overlap into the "too close" area or even overlap an entire planet. There are a handful of fixes for this:

1) Sort your incoming planets by largest to smallest. That way, if your "is close to new planet" distance is at least the radius of the largest planet you won't actually get any overlaps. You might get touching planets though, unless you also do...

2) Instead of picking a single point, pick an area of points that your planet fills. This is more computationally expensive, but the effect is that your planets won't bleed into the prepicked "not valid" areas.

Either way, you probably want to do #1 if your distance between is small and your planets are varying in size dramatically. You'd be doing a lot of computation, but the real value with an iterative algorithm like this is knowing when you can stop. With a pure random solution, if your density is high, your placing function is non-deterministic. Knowing that your map is too full (by not having any valid spots to pick from) means that you can handle that error condition, as opposed to blindly throwing darts at a board.

# Answer
> 3 votes
Your solution is fine provided that you never end up placing so many planets that the number of valid locations falls to, say, below 10% of the locations (which is very very dense.)

Let's figure out how many operations you will end up doing to place a planet given

* `x` planets already placed
* `p` the probability that a randomly chosen location is valid.

Then, the number of retries is geometrically distributed with probability `p`, and therefore the expected number of operations is `1/p`.

So, if you keep `p` above 10%, you expect no more than `10x` operations on average for each planet, or `10x^2` in total.

One optimization you can make is to keep the planets sorted by radius, and check in that order. The sorting cost will be offset by the savings from being able to stop early.

# Answer
> 3 votes
This is a really bad question, you are asking about efficiency while your real problem is that your code simply doesn't work.

In applicable situations discard and retry is a great method for heuristic generation. You can't beat the simplicity, and it's not bad performance in all cases.

Basically you try to place the planet when you have done just one check, rather than after doing all the checks. Your code is broken beyond that, but I'll leave out the details.

What you need to do, in pseudocode:

```
function calculatePlanetLocation(){
    validposition=false
    while(!validposition){
        position=generateposition()
        validposition=true
        for each planet{
            if(too close){
                validposition=false
            }
        }
    }
    planet.position=position
}

```

---
Tags: algorithm, random, procedural-generation
---


# Question
Title: How to find the bottleneck of the graphical pipeline
I've been wondering about this issue for a while. How to find the bottleneck of the graphical pipeline. Recently I've been using a program to draw massive amount of polygons in a simple scene with alpha blending (AKA grass scene). I've used two programs, one uses static coordinates and another uses rotation and translation. Both run at 60 FPS with no other heavy processes running. But when I use them together (Two windows each having same amount of grasses and grass positions) the one that uses translation and rotation runs at 10 FPS but the other one is about 55 FPS. My question is why are both running @ 60 FPS and when such thing happens why does the second one(Rotation and translation of each grass) drop about 50 FPS but the second is still 55? Sounds like a bottle-neck to me. Please let me know if you have any idea, or in a more general answer if you have an idea or paper about finding bottleneck of GPU(or GPGPU), or optimizing the graphical code for running on GPU?

# Answer
> 4 votes
The general answer is to do a frame capture and profile. Use something like NV PerfHUD or other GPU performance counters to see what the GPU is doing, and which draw calls takes time. You can then get information about what the bottle neck that draw call had.

Your case seems to be something like two programs interacting and context switching the GPU?

# Answer
> 3 votes
You can find some information in these materials:

Randima Fernando. GPU Gems: Programming Techniques, Tips and Tricks for Real-Time Graphics. Addison-Wesley Professional, 2004. **Chapter 28**

David Blythe, Brad Grantham, Tom Mcreynolds, and Scott R. Nelson. Advanced Graphics Programming Techniques Using OpenGL. Course Notes for SIGGRAPH ’99. ACM, 1999.

# Answer
> 2 votes
both running at 60FPS doesn't neccesorily mean they can both run with the same speed, there is usually a fps limiter in game engines that doesn't let fps go higher than 60fps (and that's somthing you can spot that and remove easily), so in your case maybe without this limiter the static fps wuold be around 120 and the dynamic one would be around 70, with them both running gpu can't handle both processes, assuming that your test shows even half of gpu's power is almost enough for static scene, but isn't near enough for dynamic one. and if you want to find bottleneck in your pipeline ,assuming that you have access to all your shaders source codes, you can use "nvidia fx composer". in that program you can draw your pipeline, give it all your shaders and it'll show how much time is consumed in each stage for each shader.

---
Tags: opengl, 3d, graphics-programming, c, gpu
---


# Question
Title: Competing with C++ for games programming
I'm curious as to why C++ is so popular for games development, and not other languages instead. I know you can create very fast code with it, but what exactly is it that makes it popular?

Is it just because it's fast? Is it some other feature in the language, like the OO paradigm or the portability? Is it because of all the libraries that have been created over time? Or some combination of all these (and other) reasons?

If someone could fill me in on this, I'd be very happy. :-)

# Answer
Numerous reasons:

* Big one you missed: It's portable, simplifying ports your game engine to iOS, XBOX, PS3, whatever
* It's fast
* All the SDKs support it natively
* Lots of libraries available
* Everyone writing games knows it, so it's easy to hire experienced games devs for your team
* It's trivial to embed a game engine scripting language like Lua
> 29 votes

# Answer
There are a few reasons, that I'd like to mention in addition to what @Graham brought up.

* Legacy Code - many studios have lots of C++ code, goes to your mention of libraries.
* C++ is really a high-level assembler, and has **direct** access to hardware (as direct as you can get running on top of an Operating System at least) and is quite fast. If you want, in C++ you can drop directly down into assembly language for instruction level control (not that it is always wise, its just not possible with Java, C#, Python, etc)
* DirectX and OpenGL natively support C++, most other languages have "bindings" to the underlying libraries through intermediate layers, thats not to say they aren't fast or can't do many of the same things, but it adds a layer of software between your game and the hardware.
* As @Graham mentions, lots of programmers know it, so its easy to find experienced developers, and its also quite portable, compared to C# which is stuck on the .NET Framework (there is Mono, but it generally laggs a generation behind Microsoft's implementation.)
> 14 votes

# Answer
Raw speed is the primary reason, but actually it's not an either-or decision so lots of game companies are starting to use other languages for parts of the game. Certain tasks require the computer to work as fast as possible (eg. core rendering routines) but many tasks in gameplay code don't have to run all that fast (eg. making the door open when the player clicks on it) which means it is smart to use a much simpler (and thus faster to write programs in) language for those parts. That is why many game engines are written in C++ but embed a scripting language like Lua for writing gameplay code.

The tricky thing to understand is that when choosing programming languages there is an overall tradeoff between efficiency for the computer and efficiency for the programmer. That is, which is more important to you, how quickly the computer runs the code or how quickly the programmer writes the code?
> 8 votes

# Answer
In C++ you can allocate local variables that disappear after the function ends. Usually, these are allocated on a stack.

The stack variables do not contribute to the dynamic memory allocation issues of fragmentation and overhead. Allocating room on the stack is quick and easy (just adjusting a pointer). Dynamic memory allocation usually involves searching a container for an adequate block of memory, marking the memory, then tagging it as occupied. Deallocation involves adding the memory block to a container, and possibly merging it with existing blocks. A lot more overhead than just changing a pointer.

Java and C# allocate memory dynamically, except for primitive types. These languages depend on a run-time environment that will mark a variable to delete, then run a garbage collector at random (unscheduled) intervals to reclaim the memory. In general, the programmer has no control as to when the variable will be tagged for deletion nor when it will be reclaimed (reclamation of used memory is an advanced topic that most C++ and Java programmers don't experience).

The speed of C++ is primarily due to its direct translation to executable code. Java and C# are compiled to an intermediate code which is then interpreted by a virtual machine. In general, interpretive languages are slower performers than directly translated languages.
> 3 votes

# Answer
Games were once written in machine language, because they had exotic hardware for which there was no compiler. The hardware also lacked features that C programmers take for granted, such as efficient 16-bit integer math.

Once games settled on familiar hardware, C compilers became available and in a short time all games were written in C.

C++ seemed like a good idea at one time, and most games are C++ today, but engineers are now mumbling about a return to C, and that might actually happen. I would love to work on a game in C, and so would many coworkers. There's no feature new to C++ that I think improves games.

It would seem now that computers are 1000x faster than a few years ago, a high level language would reduce development time ($) making C obsolete.

This has not happened because game buyers know that the hardware is 1000x better, and want to trade their dollars for a game that looks and sounds 1000x better. This removes the slack from the system that a high level language would consume.

Performance requirements in games are brutal. A new frame of graphics must be rendered in under 33ms (or 16ms!) without fail. Everything the hardware does must be accounted for, so that this budget can be met. Any language that goes off and does something with the hardware that the programmer doesn't understand or expect is going to make it very hard to meet this budget. This is an automatic minus against anything high-level.

Game programmers not only work in a low-level language, but they shun high-level data structures and algorithms too. Games typically don't have linked lists and seldom have trees. There is a movement towards avoiding pointers whenever possible\*. Any algorithm with more than O(N) time or O(1) space tends not to find wide use.

\*If a pointer doesn't cause a cache miss, then why spend 32 bits to store it? If a pointer does cause a cache miss, best get rid of that cache miss.
> 3 votes

# Answer
Every programming languages have strengths and weaknesses across a range of factors. Examples of these factors are:

* Speed on a particular platform
* Memory usage on a particular platform
* What functionality it exposes more readily
* What platforms it exists on
* What considerations a programmer has to take on-board

One of the most important factors a game programmer cares about is performance. They want to produce an interactive experience, which means it has to be reactive and able to output as much useful (or interesting) data as possible. You want to know how much health you have at any time and don't want to wait for it. And if you click a button, you expect a gun to fire or your character to jump when you say so. A little lag can interfere with this interactivity so you need performance.

Another important factor is preferring to program in the language of the problem, rather the language of the implementation. A game programmer wants to deal with humans, orcs and race-cars, not memory register ED0. They still want the option of diving into the implementation details if they need performance, but it'd be great if for the most part they can deal on the level of the entities in their game world. They have enough to worry about simulating the game world without having to always care about how a linked list works.

C++ fits these two primary factors very well. You can have the performance benefits of assembly or C code with the expressiveness of objects. To see why this is a natural fit for games, compare with some other language options:

* **Assembly:** This is raw power. What you write is basically what the CPU does. But at every stage you need to know what is going on with registers and the effect of this, and it never looks like the entities in your game world. The programmer has to make the mental correspondence of what their code does versus what happens in the game. This can be quite a mental overhead.
* **C:** Here we have good performance, but we can leverage the experience of gurus to get standard things done (like allocate memory, operate on strings and use standard mathematical functions). We get closer to expressiveness here, but the language more or less forces you to focus on the implementation because you can really only operate on normal data types. Everything is really a char, an int or the like. structs, pointers and arrays can hold things together, but still have to think about the internals.
* **Java:** We leapfrog over C++ and get to Java. Java pushes further away from implementation details. In fact, much of the time you don't get access to the lower levels. Java abstracts away much of the implementation details (eg. what CPU or OS you're using) for the reason that it wants to be cross-platform. You can't access the details because they are not there. You don't program for the computer, you program for the platform (the Java platform, which happens to exist on most computers). Moreover, Java has an arguably better language for dealing in the language of the problem than C++. The trade-off is you can't optimize for a particular computer. Whether this makes a practical difference or not comes down to the specifics of the program and the computer.
* **Game scripting language:** By this I mean something like UnrealScript, or custom scripting languages strapped onto a game engine. In these you have no access to the underlying engine. You delegate performance considerations to the engine, leaving yourself free to worry about making a game. It's easier to write the game, harder to optimize its performance yourself.
* **Haskell (or your favourite obscure language):** Any Turing-complete programming language is equivalent to any other. So while you *can* write any program in any language, you make tradeoffs, some objective, some subjective. A language like Haskell is more focussed on working in a mathematical spirit. The problems it is geared towards are somewhat different the problems faced in games. It doesn't mean it can't or shouldn't be used for games, it's just its not easily suited to it.

The last point is that some of this is historical and political. Many flame wars have been fought between the different programming languages. C# for example might be just as suitable to games development, but it came after C++. Or people don't like that it's from Microsoft. Some people made the move to C#, some didn't. Some people still program games in BASIC, Pascal, and C. Whatever programmers are comfortable with, they'll stick to. Games programmers have mostly been comfortable with C++, possibly because they grew up with C and C++, and it met their needs. If the computer industry is in a state where Java's performance and uptake satisfies enough people, then maybe Java would be the de facto standard game development language.
> 3 votes

# Answer
Legacy and momentum.

Once upon a time code was written in assembler for ultimate performance. As compute power increased, compiled languages became more viable, and C offered the best compromise between power and productivity, at a very basic level being little more than a macro assembler.

C++ was just the natural successor to C. You throw away no former code or knowledge, yet have the potential to expand into new methodologies. C++ is ultimately very flexible, and I've yet to see a design paradigm that can't be at least simulated in C++, whilst being able to maintain near total control over performance.
> 2 votes

# Answer
If you're developing for the consoles, you have no choice: the professional SDKs only come in C++ flavors. Usually they also have C access to most things.

Because many developers are Consoles + PC, it makes sense to do all their PC work in the same language and directly share tech.

Because that's where the pro industry lives, and most everyone wants to be a part of that, most game programmers are C++ programmers.

Because all of that happens, most engine developers are C++ developers too, so when evaluating professional grade engines almost all your choices will be C++.

It's all a big self sustaining engine. Disrupting it would require more than just technical advancement.
> 2 votes

# Answer
FWIW: C# is gaining in popularity for game development. See Miguel de Icaza's blog post. Very interesting read, IMHO.
> 2 votes

# Answer
Although I'm fairly heavily anti-C, C & C++, the one thing they DO have that few other languages have is complete control over the platform it's running on, you can be sure exactly what will be going on at all times, no GC, no glitches.

This isn't as important these days, but it can be for underpowered platforms.

On PC/Mac/Linux it's probably the least portable language you'll encounter these days, and the speed bonus is no longer that much of a difference--Minecraft (Java) is smooth and works on pretty minimal platforms (and any OS) with a single executable--I've yet to see a low-manpower indi C/C++ app with as much functionality and as few bugs, let alone work on three platforms.

So at this point I'd say that most of it is inertia and the conception that real games are always done in C/C++, although the ability to "port" to iPhone and consoles is significant (Even though I'm fairly sure most of the UI of games take a LOT of effort to port except between Windows and XBox).
> 2 votes

---
Tags: c++
---


# Question
Title: Perfect fit for isometric tiles in AS3 with BitmapData
I'm creating a game which uses 320x160 sized isometric tiles. I've got an editor that allows me to take loaded in tiles and plot them. The map size is 8x8, and instead of placing down 64 movieclips, and then moving them around, I thought I'd use the bitmapData.draw function to plot these mc's directly to a bitmap (as I'm not doing anything with them after they are put down anyway).

That works fine apart from there's a small line appearing between the tiles, along the edges. I think this has something to do with anti-aliasing, because when I export the tile as a .png with no smooth, and use that tile in my editor, there's no faint line between the tiles, but that also makes the tile overall look pixely, so I'm at a bit of a loss.

I want the edges to fit perfectly together so need to be pixel perfect, but I want the interior of the tiles to be smoothed, any ideas? unless there's a way to solve this with the bitmapData approach in itself? The only thing I can think of right now is to make the tiles slightly bigger than they need to be so they overlap slightly, but that's a bit of a fudge, which I want to avoid if possible.

# Answer
You should make sure the alpha channel of your tile is crisp.

So if we zoom in a bit, the alpha should look like this:

Not like this:

If you have anti-aliased alpha edges like before, you'll always see bits of the background shining through where edges meet. A good way to get the transparency right, is by using "layer masks" in Photoshop or use the polygonal-lasso tool and disable "Anti-Alias".

**Edit:** I'm sorry, I just re-read your question and saw that your tiles are actually MovieClips, and not Bitmaps. One option (as indicated in the comment below) is to save the image as PNG, with a aliased alpha channel. Another option would be to use the BitmapData.copyPixels method and provide a separate (aliased) alpha channel as the `alphaBitmapData` parameter. That works best, if your tiles don't come with an alpha initially and are filled with the border-color, as in the following image:

On the left, there's the tile color (which can still be a MovieClip) and on the right, there's the alpha channel which is aliased and can be provided separately to the `copyPixels` method.
> 4 votes

# Answer
I just thought of this, you could try using a game engine or tiling engine like Flixel or FlashPunk. I haven't used them yet myself, but I have been looking into it.
> -1 votes

---
Tags: actionscript-3, tiles, isometric
---


# Question
Title: What causes some computers to have no or slow OpenGL, and how to fix it?
I am using Java with JOGL to create OpenGL enhanced 2D graphics. The graphics operations I use are nothing fancy, and should be supported by almost any recent graphics card. For example, my game runs great on a Netbook.

I was hoping the game would run on most computers. It runs fine on my own computers. However, I found some computers have very slow performance (apparently software fallback, yielding about 2 frames per second). I ran a LWJGL app on one such computer. It doesn't run at all (it reports something like org.lwjgl.LWJGLException: Pixel format not accelerated, you can find various forum threads complaining about this but no apparent solutions, except the suggestion that it is a driver problem). Other OpenGL software does not seem to work, either. I also found that my Flash version of the game with exactly the same graphical effects performs pretty well full-screen on that same computer. The computer in question has a recent ATI card but unfortunately I have no access to the driver manager.

The problem appears fairly widespread. I think it is very unfortunate that OpenGL does not always provide access to graphics features found on most computers. This makes it less attractive for casual 2D games, which I expect to run on any computer.

Did any of you run into this problem and manage to fix it? AFAIK, both NVidia and ATI provide OpenGL as part of their standard driver sets, but maybe there are some exceptions? Is this problem caused by third party drivers not supporting OpenGL, and can the problem be fixed by installing better drivers? How many other graphics cards are out there without OpenGL drivers?

**EDIT**: As a final note, I can conclude that OpenGL is just not well supported on Windows machines. Microsoft seems to have been doing their best to keep it off their platform, for example by deliberately leaving out OpenGL drivers in some Windows driver bundles. Get the vendor drivers, and you get OpenGL; get the standard drivers that Windows downloads for you, and you don't. This has been causing no end of trouble for others as well. For example, for implementing WebGL, Web browsers use Angle, which is an OpenGL ES emulator for DirectX. So, what we'd really need is something like Angle, only for full OpenGL.

# Answer
This is a common problem even on new GPUs when drivers are not installed. OpenGL version is 1.0 1.1 and is running in software mode.

Install/update GPU drivers and add version query to your application. If returned OpenGL version is below 1.1 then it is definitely missing drivers.
> 5 votes

# Answer
I'm just guessing here, but are you using shaders? What video card was in the computer you tested on that threw the exception? A lot of older built-in Intel cards don't have pixel shader support.

Your only real recourse, if that's the case, is to provide a fixed function fallback.
> 1 votes

---
Tags: opengl, lwjgl, jogl
---


# Question
Title: Google Web Toolkit: Ever used for making games?
I've recently come across GWT (Google Web Toolkit) and have been amazed by it. I was wondering if anyone has ever put it to use making a video game? And if they did, what their experience was, whether it was worth it and whether the game was any good.

# Answer
You might be interested in a talk from this year's Google I/O about using GWT, WebGL, and App Engine to build game tools. I would never have imagined that could be a really killer combination but was really surprised at how awesome it looked.
> 4 votes

# Answer
In addition to the EA game mentioned in amitp's comment, Rovio used GWT to port "Angry Birds" to the web (with a bit of Flash to work around HTML5's sad audio situation).

There was a dzone article about it not to long ago: "Web Gaming Technologies: Angry Birds' Cross-compiled Java Versus Native JavaScript".
> 1 votes

---
Tags: web
---


# Question
Title: OpenGL ES 2.0: Controlling Transparency in Fragment Shader
The following is the OpenGL ES 2.0 simple **GLSL Fragment Shader**, I use to place textures on polygons, to render 2D sprites.

```
varying mediump vec2 TextureCoordOut;
uniform sampler2D Sampler;

void main()
{
gl_FragColor = texture2D(Sampler, TextureCoordOut);
//gl_FragColor = vec4(texture2D(Sampler, TextureCoordOut).xyz, TextureCoordOut.w * 0.5);

}

```

The fragment shader places voxels with alpha information taken from the source 2D texutre(.png image). Apart from alpha information, I need to control overall polygon/sprite transparency to achieve **Fade In/Fade Out** effects.

Could you show me, please, how to **modify the above shader** to control the overall transparency, besides the alpha information?

*Note: The commented out line is used for my attempts to achieve the transparency. I wish to **combine** both the alpha information with the overall polygon/sprite transparency.*

Thanks.

# Answer
> 4 votes
This is probably cleaner solution, which also doesn't require to ask texture unit two times.

```
void main()
{
  gl_FragColor = texture2D(Sampler, TextureCoordOut);
  gl_FragColor.a *= 0.5;
}

```

(maybe compiler does that for you, but what if not. Especially on the opengl-es device performance difference *may be observed*)

# Answer
> 2 votes
Apparently, I found the soultion.

*This is the correct line in Fragment Shader:*

```
    gl_FragColor = vec4(texture2D(Sampler, TextureCoordOut).xyz, texture2D(Sampler, TextureCoordOut).w * 0.5);

```

Thanks anyway.

---
Tags: opengl, opengl-es, glsl
---


title: Flash Game not working on Android

text:
# Question
Title: Flash Game not working on Android
I am not sure if I will be able to provide enough information for someone to answer this question, but any ideas might help.

I am creating a tower defense game in Flash and I eventually want to make it run on Android. Just for testing purposes, I have been running it on Android's browser and different Android .swf player apps.

Recently, the game stopped working correctly. When it gets to the second wave of enemies, they get about four tiles in and stop moving. I can get them to start moving again by constantly clicking on parts of the screen. It's almost like the game loop has quit updating.

Trying to solve the problem, I have updated the gameloop from Flash's standard events to a NativeSignal event (didn't solve the problem but the game runs much faster overall).

The game works fine on my PC, I can't figure out the Android problem though. Any ideas or help would be appreciated. I didn't want to supply code since I wouldn't know where to start that would be helpful.

# Answer
> 0 votes
I've had exactly the same problem with a game of my own. In my case it seemed to happen at random moments. I think this happens when the enterFrame handler does not finish the frame before new enterFrame events happen. In that case the result is not displayed properly unless other events also happen.

I lowered the frame rate, and the problem seemed to have gone away (I didn't test it thoroughly, because I eventually ported the game to Java). I didn't test on Flash 10.3 yet, though. Maybe they fixed the problem there. I am interested to see if this works for you.

# Answer
> 1 votes
I'm not familiar with running flash content on Android, but I can think of two things that could cause your issue:

1. Make sure your code is error free. The flash player that's usually installed in desktop browsers is quite forgiving in that regard and sometimes continues to run, even if an error was thrown. Install the debug-version of the flash player for your browser and check if you get any error messages (usually they will open in a popup-window).
2. Mobile devices tend to have a lot less memory available for apps than the average desktop PC. Make sure your game is memory efficient and doesn't leak memory! You can leak memory with flash pretty easily, even though it's managed code.

I don't know what software you use to develop that game. If you're using FlashDevelop or FlashBuilder, you can profile/debug your game and look for memory-leaks and errors.

# Answer
> 1 votes
I've stumbled into the very same problem lately. The game advanced only when touching the screen. From what I have found in various articles, it may have something to do with the CPU throttling that the Flash Player uses on mobile devices. Going into fullscreen removed the problem for me.

# Answer
> 0 votes
maybe it just stuck in some function in the main loop so that any other event(like touch event) make them step one point but the main loop event doesn't happen any more.

# Answer
> 0 votes
I am not sure what was happening. I am sure one of the answers was probably the problem, but I couldn't find it specifically. I rewrote my game loop and a lot of the other code that worked with it and the problem is gone.

---
Tags: flash, android, actionscript-3, game-loop, tower-defense
---


# Question
Title: What is the name of the perspective style of games like Final Fantasy 6, Chrono Trigger or Alundra?
What is the actual term for the 'top-down' style of the Super Nintendo games such as Final Fantasy 6, Chrono Trigger, et cetera. I'm looking for the equivalent term of:

* 'isometric' - (Jaggered Alliance, Final Fantasy Tactics, Fallout),
* 'first person' - (Half Life, Doom, Quake),
* 'birds eye' - (Grand Theft Auto)
* ? insert term here ? - (Final Fantasy 6, Chrono Trigger)

# Answer
The terms you have used in your question are more colloquial than precise or definitive, so comparing against them is not necessarily useful. Technically you're comparing different types of 'projection', plus the viewpoint that the projection is done onto.

Final Fantasy 6 uses an orthographic projection, though a very specific one that is perhaps easiest described as a degenerate oblique projection where the receding surfaces are drawn at a 0° angle rather than a more illustrative 30° or 45° (as in Ultima VII). The viewpoint is typically from above and offset somewhat from the area being viewed.

GTA1 uses a fairly standard orthographic projection. The viewpoint is directly above the subject.

First person games use perspective projection. This projection is also used for most third person games rendered in 3D. In 1st person games the viewpoint is placed at roughly head height on a notional person, but in 3rd person games the viewpoint might be placed behind a person's shoulder, or high above the world, or in any arbitrary position.

Isometric games are, of course, in an isometric projection. However, Fallout 1 and 2 are not technically isometric - they are trimetric projections. You can see the difference in how Fallout is slightly rotated compared to a typical isometric game. For a game to be isometric, the angles between the 3 axes need to be equal, ie. 120°. Examples are Final Fantasy Tactics and Sim City 2000. The viewpoint is pretty much the same as for the oblique projections.

Oblique, orthographic, and isometric are all types of parallel projection where lines that would appear to converge in real life when viewed in perspective, are rendered as parallel lines instead.
> 20 votes

# Answer
I hear it called 3/4 perspective.
> 1 votes

# Answer
I'd personally call that an overhead view.

Relevent - Wikipedia - Video game graphics
> 0 votes

---
Tags: graphics, graphics-design
---


# Question
Title: What is your Unity 3D physics engine budget for iOS games?
I'm testing Unity for a game that I'm building, and I've touched its limit.

My test scenario: a wanna-be house with 200 elements (cubes rescaled) no textures, box colliders and rigid bodies for each "cube" and fixed joints to hold them together (400+ fixed joints). The house is on a plane, and above it I put 2 sphere at different altitudes, spheres which will crash in the poor house.

This moves very slow on an iPod Touch 3rd generation. Therefore I'm looking for some documentation to create a reasonable budget for the number of polygons, physics collisions and so on. What is your recommendation?

# Answer
I would have posted a comment but I don't have enough Rep. to :(. Having working with Unity3D on PC we came into problems with the phsics engine when there were too many fixed joints; suprisingly there are very greedy, I'd guess even more-so on iOS as the Physics is CPU dependant.

The guidelines for Unity are generally quite good, you could check out this link for optimizing performance in iOS.

They obviously tell you to use the Profiler, which I also recommend, if you can't go Pro, you'll just have to keep on testing :/.

Oh and as you are using fixed joints to attach the walls, you could maybe use capsule colliders with high friction to simulate the bricks and change this at real time with a box collider once the brick is not longer attatched to any others. (Any two bricks attached should still have a decent simulation even with capsule colliders.)
> 3 votes

# Answer
My recommendation is to utilize a profiler or some other form of metrics gathering, that way the physics budget you arrive at will be tuned for your specific game -- the numbers others provide for their games may not apply so well for your game. This is especially true in general, but it tends to hold even if you're using common technology like Unity.

Xcode ships with Sampler and Shark, which can be used to profile applications (although maybe not Unity ones, at least not usefully). You may be able to inject home-grown profiling/timing gathering solutions into your code as well, provided you have any.

Failing that, I'd take a divide-and-conquer approach. You say your initially-described scenario runs poorly, so I'd start with that and halve one of the numbers (either the number of cubes, the number of joints, et cetera), and see how that performs. Try to change only one variable at a time. It's pretty ad hoc, but it might be what you need to do if you can't get the pro trial that comes with the Unity profiler.
> 1 votes

---
Tags: physics, unity, testing
---


title: Storing, loading and editing a level

text:
# Question
Title: Storing, loading and editing a level
I'm trying to find useful information on creating game levels in a reasonably efficient way. Additionally, information in setting up a fairly painless way to edit this information would be handy (the closest I've come is some monstrosity in Flash; I would place the parts onto the stage, and run a script reading all the platforms, triggers and what have you, into an XML document).

Google hasn't been to terribly helpful in finding what I need (probably what terms I'm using as I'm not sure exactly how I would refer to this). I'm hoping there may be someone here who knows of a good solid article on handling the data for a level.

I've made a few attempts in previous projects (the latest being in Flash using XML), and I often run into issues with performance (in my case, I narrowed it down to having to many objects loaded, and started culling what was outside my view, was still slow though...).

---

To clarify a bit. I'm not afraid of investing time in developing tools. I don't have a specific game I am making this for so much as I am wanting to learn about the theory behind a level editor and the files it would generate to be used as a level. I'm looking to understand what goes on in a program and thus far have been un-successful in finding anything to help educate me on what makes such a system tick.

I am particularly interested in knowing how to make one that's 'good' rather than 'works'. I've already gotten something working in XML on my own, however it was poorly structured and excessively slow for relatively small levels. I am sure there are better ways to organize the information for loading and using on the screen, its more a matter of me being unsure what to use. I've heard talk of using binary space trees, quad or oct trees, however I haven't found much related to using them in a tool. (Most of what I have found is academic and more or less to abstract to make use of outside of theory)

# Answer
**The Tools**

What you use to create levels -- and assets, in general -- for your game will vary wildly depending on the type of game you are making and the technology you are making it with. Sometimes the most efficient thing to do is leverage tools that other people have written, such as the aforementioned mappy. If your levels are simplistic enough you might even be able to do them in something like MS Paint, assigning particular tile values to particular colors and basically just painting the image. You could even do layers like this (with different images) -- it's not elegant, but it works.

Of course this assumes you're building a 2D, tile-oriented game. When you get into the realm of 3D, there are far fewer decent generic level editors -- commercial games tend either build proprietary level construction tools, or use 3D modelling software and heavily massage the output via exporter scripts or build-time processes. So you, too, may need to roll your own.

In doing so its important to select a language and toolchain that is well-suited to the task (and that you know, or can learn reasonably quickly). C++, for example, probably is a poor choice for building a rich GUI experience due to the relative low-level nature of the language and even of the available third-party GUI APIs. Flash probably isn't the best choice because it's designed as a content presentation system first and foremost, and probably won't be ideal at overly complex interactions -- you may need to write a lot of code to make it do the things you want. The cost of this can be amortized a bit if your game is also in Flash and you're tying directly into code or functionality the game needs anyhow, though.

I build most of my tools in C# using Windows Forms or WPF (I'd recommend the former, as the latter has a much more painful relative learning curve and once you get beyond Happy Exampleville in WPF, things tend to get pear shaped real quick). You can usually throw something together in a matter of a few minutes and make it fairly robust within a few hours.

The advantage to choosing a tech platform different than your game is that you can choose one that lets you develop the tools far more quickly. The disadvantage is that the tools are disconnected from the game (for example, they don't share the same renderer so in-game previews aren't possible) *unless* you also spend the (nontrivial) effort to develop an interop layer for your game framework.

**The Data**

XML or JSON (I prefer the latter) is actually a reasonably good choice to start out, because they are both text-based, human-parsable data and you can iterate on the format quickly as you develop it. If you're not sure what exactly to put *in* the format at first, one way to approach the problem is to think of what information you'd like to have when rendering or interacting with the level in your gameplay logic code, and then make that what you store.
> 4 votes

# Answer
For simple tiled games, **mappy** is quite useful and allows you to create multiple tile layers and export them into many different formats.

A quick Google gives a couple of other editors http://www.mapeditor.org/ and http://tilemapeditor.com/.

I think it's often a good idea to choose an editor that already exists, you can check whether the editor works for you and if the output data is good enough for your game engine.

You can them choose what suits you best before making your own editor, should you need it.

XML will generally produce a larger file format that will also take longer to load but is often used for its flexibility. If you are running into runtime problems though, maybe you should reconsider how your objects are defined.

For example you can create bigger blocks where possible, this will crete fewer objecs. You can also optimize some things at load time to 'cluster' tiles together.
> 2 votes

# Answer
Its not really an answer you want to hear but a lot of commercial games companies spend as much time on the tools as they do the game.

In a book I recently read the author stated that the team spent a year and a half on the tool such as level editors and graphic tools before they started the game engine.

Blizzard have a department of 30+ people full time developing tools for the programmers. Its a career choice in itself.

Try looking for "game resource editing tools" and derivatives of that but most of the ones out there that are any good output specific file types.
> 0 votes

---
Tags: levels, map-editor
---


# Question
Title: How to Interpolate between two game states?
What is the best pattern to create a system that all the objects positions to be interpolated between two update states?

The update will always run at the same frequency, but I want to be able to render at any FPS. So the rendering will be as smooth as possible no matter the frames per second, whether its lower, or higher than the update frequency.

I would want to update 1 frame into the future interpolate from the current frame to the future frame. This answer has a link that talks about doing this:

Semi-fixed or Fully-fixed timestep?

Edit: How could I also use the last and current speed in the interpolation? For example with just linear interpolation, it will move at the same speed between positions. **I need a way to have it interpolate the position between the two points, but take into consideration the speed at each points for the interpolation.** It would be helpful for low rate simulations like particle effects.

# Answer
> 23 votes
You want to separate update (logic tick) and draw (render tick) rates.

Your updates will produce the position of all objects in the world to be drawn.

I will cover two different possibilities here, the one you requested, extrapolation, and also another method, interpolation.

1.

**Extrapolation** is where we will compute the (predicted) position of the object at the next frame, and then interpolate between the current objects position, and the position that the object will be at next frame.

To do this, each object to be drawn must have an associated `velocity` and `position`. To find the position that the object will be at next frame, we simply add `velocity * draw_timestep` to the object's current position, to find the next frame's predicted position. `draw_timestep` is the amount of time that has passed since the previous render tick (aka the previous draw call).

If you leave it at this, you'll find that objects "flicker" when their predicted position didn't match the actual position at the next frame. To remove flickering, you can store the predicted position, and lerp between the previously predicted position and the new predicted position at each draw step, using the elapsed time since the previous update tick as the lerp factor. This will still result in poor behavior when fast moving objects suddenly change location, and you might want to handle that special case. Everything said in this paragraph are the reasons why you *don't* want to use extrapolation.

2.

**Interpolation** is where we store the state of the last two updates, and interpolate between them based on the current amount of time that has passed since the update before last. In this setup, each object must have an associated `position` and `previous_position`. In this case, our drawing will represent at worst one update tick behind the current gamestate, and at best, at the exact same state as the the current update tick.

---

In my opinion, you probably want interpolation as I've described it, as it's the easier of the two to implement, and drawing a tiny fraction of a second (e.g. 1/60 second) behind your current updated state is fine.

---

Edit:

In case the above isn't enough to allow you to perform an implementation, here is an example of how to do the interpolation method I've described. I won't cover extrapolation, because I can't think of any real-world scenario in which you should prefer it.

When you create a drawable object, it will store the properties needed to be drawn (i.e., the *state* information needed to draw it).

For this example, we will store position and rotation. You may also want to store other properties like color or texture coordinate position (i.e. if a texture scrolls).

To prevent data from being modified while the render thread is drawing it, (i.e. one object's location is changed while the render thread draws, but all others have not been updated yet), we need to implement some type of double buffering.

An object stores two copies of it's `previous_state`. I will put them in an array and refer to them as `previous_state[0]` and `previous_state[1]`. It similarly needs two copies of it's `current_state`.

To keep track of which copy of the double buffer is used we store a variable `state_index`, which is available to both the update and draw thread.

The update thread first computes all properties of an object using it's own data (any data structures you want). Then, it copies `current_state[state_index]` to `previous_state[state_index]`, and copies the new data relevant for drawing, `position` and `rotation` into `current_state[state_index]`. Then it does `state_index = 1 - state_index`, to flip the currently used copy of the double buffer.

Everything in the above paragraph has to be done with a lock taken out on `current_state`. The update and draw threads both take out this lock. The lock is only taken out for the duration of the copying of state information, which is fast.

In the render thread, you then do a linear interpolation on position and rotation like so:

`current_position = Lerp(previous_state[state_index].position, current_state[state_index].position, elapsed/update_tick_length)`

Where `elapsed` is the amount of time that has passed in the render thread, since the last update tick, and `update_tick_length` is the amount of time that your fixed update rate takes per tick (e.g. at 20FPS updates, `update_tick_length = 0.05`).

If you don't know what the `Lerp` function above is, then checkout wikipedia's article on the subject: Linear Interpolation. However, if you dont know what lerping is, then you probably aren't ready to implement decoupled update/drawing with interpolated drawing.

# Answer
> -2 votes
This problem requires you to think about your definitions of start and finish a little differently. Beginning programmers often think of change in position per frame and that is a fine way to go in the beginning. For the sake of my response, let's consider a one dimensional answer.

Let's say you have a monkey at position x. Now you also have a "addX" to which you add to the monkey's position per frame based on the keyboard or some other control. This will work as long as you have a guaranteed frame rate. Let's say that your x is 100 and your addX is 10. After 10 frames, your x += addX should accumulate to 200.

Now, instead of addX, when you have a variable frame rate, you should think in terms of velocity and acceleration. I will walk you through all of this arithmetic but is is super simple. What we want to know is how far you want to travel per millisecond (1/1000th of a second)

If you are shooting for 30 FPS, then your velX should be 1/3rd of a second (10 frames from the last example at 30 FPS) and you know that you want to travel 100 'x' in that time so set your velX to 100 distance / 10 FPS or 10 distance per frame. In milliseconds, that works out to 1 distance x per 3.3 milliseconds or 0.3 'x' per millisecond.

Now, everytime you update, all you need to do is figure out the time elapsed. Whether 33 ms have passed (1/30th of a second) or whatever, you just multiply the distance 0.3 by the number of milliseconds passed. This means that you need a timer that gives you ms (millisecond) accuracy but most timers give you this. Simply do something like this:

var beginTime = getTimeInMillisecond()

... later ...

var time = getTimeInMillisecond()

var elapsedTime = time-beginTime

beginTime = time

... now use this elapsedTime to calculate all of your distances.

---
Tags: design-patterns, interpolation, fixed-timestep
---


# Question
Title: Balancing upgraded units vs. non-upgraded ones
The essence of this question is basically this: consider a strategy, RTS or a tower defence game, where you have the choice to build a new unit or to upgrade an existing one. The upgraded unit is definitely worth more than a non-upgraded one, but by how much?

In designing a upgrade path, how do I design it such that

1. Upgrading is worth the time and effort
2. However, upgrading doesn't becomes too über that the player forgo building new units?

For example, in *Defence Grid*, a glance at a number shows that two Level 1 Gun turrets do less damage output than a Level 2 Gun turret; however there are advantages to having 2 towers over 1 (say, you need to cover two different paths).

# Answer
In Sanctum (tower defence) you get the most damage for your money by building low level turrets. However, depending on how you build your maze not all turret positions will be equal, some will be able to shoot for long periods of time, others not so much, so the optimal strategy would be to build high level towers at the best points, low level towers at the lesser points, and nothing at the very worst points.

RTS games are quite different, the whole position aspect doesn't exist for mobile units. A typical formula is to make the high level units overall better for their price, but make it so that you have to do an initial investment in order to be able to build them, that could be do some research that takes time and cost money, or build a structure to enable the construction. So the player will have to balance when to move for the higher level units, which at that point will decrease the immediate unit output and thus temporarily weaken the player. Another thing to do is make the strengths of the units different rather than one just being stronger than another, they will have different perks making a strategy that combines them and is capable of adjusting depending on what the enemy does optimal. This is for instance very typical for Blizzard RTS games, but it takes a lot of skill, time and testing to do just right.

And finally an anecdote:
The optimal multiplayer strategy in the RTS game Earth 2150 is to choose the Lunar faction and build nothing but Lunars equipped with machine guns. This is basically the cheapest fighting capable unit in the game, whenever taking fire it's gone almost instantly. But it's cheap, and very quickly produced, so you can field an abundance before the opponent has a chance to do anything serious.

Not a lot of people ever discovered this on their own, everyone just presume that it's a worthless unit, because that is what a lot of other games and campaign mode has taught them.

Balancing is a really tough job, and it's very easy to fail in anticipating a simple winning strategy.
> 6 votes

# Answer
You should consider the price and the time it takes to upgrade, if you have a fixed upgrade/build time for every unit you can ignore that.
The value(for the player) should scale with the price he pays for it.

You should also consider how much time it needs to gain a certain amount of money.

Just a few thoughts.
> 1 votes

# Answer
upgrading usualy doesn't consume space but building some new guns need more space so if I were to balance them i would put higher price for upgrades, and besides i think it's logical that upgrades take less time than new building, but that's for you to decide, so i think for an upgrade that duplicate a tower's power i would set 1.2 of the tower original price and 0.9 of it's building time. the same senario goes for rts games, except map size limit and it's usualy population limit that prevents you from building lots of things.
> 1 votes

# Answer
Damage to the enemy from a tower is a combination of damage amount * field of fire area.

As a player, when deciding to either upgrade an existing tower or build a new tower, you would do a rough calc of field of fire area * damage strength * cost. For towers that have small field of fire area, it is usually better to build new elsewhere, but for well located towers with above average field of fire area, you would want to upgrade.

As a designer, create opportunities for both so your players will have to strategize about it or experiment with it or at least mentally engage himself in that concept. Create some borderline locations too to try to trip up the player a bit before they catch on.
> 1 votes

# Answer
Another thing not mentioned of course is rate of fire / recharge speed.

This can apply offensively or defensively (ie shields).

Falling back on the tower examples noted already, and just being quick and loose with costs (no analysis, just off the cuff) you could have more low level towers at fire power 1, rate of fire 1, range 1 for cost 3 or you can have an upgrade with fp 2, rof .75, range 1.25 for cost 4.

Now the scenario where more low level is better is the scenario where you have swarms of enemies. That 3/4 rate of fire might just require you to build more towers at more cost.

The high level becomes more effective as enemies requiring multiple hits start to appear, now you're getting 2 shots for the price of 1.

To turn this into a defence strategy think about varying hit points or shielding (tower defence where the enemies attempt to destroy your towers, not just bypass them?)

Hope this helps
> 1 votes

---
Tags: game-design, balance
---


# Question
Title: What does it really take to make an MMORPG/Where should I go from here?
Foreword: I am posting this on answers.onstartups and gamedev.stackexchange because the expertise from each area will likely contribute useful information. Also, I saw similar questions to this, but I still want advice. So I'll change this question to: where should I go from here? What's the next step?

So this morning I'm taking a shower, when suddenly I have an epiphany! The greatest idea I ever had, and it's about a dynamic 3D persistent-world MMORPG that breaks from the classic MMO in all senses (for business reasons I will not share any details). So I ran out of the shower, grabbed the graph paper in my room, and started jotting everything down.

Then I got stuck on something. I realized I REALLY want to make this happen, but don't know where to start. I'm going to college as a freshman in the fall, and I think that by the time I get out, it will be too late. Someone else will already have done it or be making it (long development process). I thought, do I go to a big game company, take out a big loan, go to California and get workers?

So this brings us back, what does it REALLY take to make a Massively Multiplayer Online Roleplaying Game? (considering, 3D, dynamic world, servers, sites, marketing, and everything else I'm missing). What's the next step?

# Answer
> 3 votes
My sincere advice to you: Start a blog where you in detail describe every aspect of the game you want to make. If you are lucky you will be able to gain a following during the next couple of years, and might even be noticed by some of the people in the industry who can help you further.

The rationale here is that if you can come up with one good idea, you can also come up with another, and as such the idea itself is not really of value for you unless you are able to translate it into something more tangible like connections and reputation.

If you a uncomfortable sharing your idea, write the blog anyway and just keep the posts private. This will help you articulate the idea, and expose flaws and missing parts.

The thing is that in your position it is very unlikely that you will receive any serious help from the industry. They don't need new ideas, they need solid products that will generate revenue year after year.

# Answer
> 4 votes
Ideas are worthless in the (narrow) capitalist sense of the term.

You can't sell an idea; there is no demand for them.

There have been many ideas for all different forms of MMOs. However, the enormous cost of building an MMO can bankrupt even fairly large companies. Deviating too far from the norm when tens or hundreds of millions of dollars are on the line is hard to justify. There are thousands upon thousands of successful games. There are only a handful of successful MMOs.

**That is why it's easy to think of radically different MMO concepts.**

Your idea might be awesome, and it might be the concept for the greatest game ever, but that alone is perhaps 0.1% of what's needed to produce a successful game.

My best advice for you, is to go to college, get a job, learn to work with a team in a company, and then start working on a smaller version of your game that isolates the "toy" concept that makes your game fun and unique. At that point, you'll be in a better position to decide what's necessary to build your amazing game -- and I promise you, your idea of what constitutes an amazing game will be very different at that point.

---

I have a binder with over 100 pages of documentation for a game that I started writing years ago. It is very comprehensive -- from hundreds of possibilities for abilities, to the foundations of skill systems, to concept art for NPCs, to implementation level algorithms.

http://www.olhovsky.com/2011/03/dbp-2011-entry-started/

Two years later, I've sobered up about how hard it is to make a fun game concept. It requires iteration on design and testing -- lots of it. If you think that you know that your game is fun after a few minutes in the shower, then I'm sorry, but you don't know!

# Answer
> 3 votes
The best advice that I've ever seen is to SHARE your ideas. Game companies with the resources to steal your game idea are more unlikely to steal it the more original it is simply because your idea isn't proven.

The more you share it and keep people updated on the progress the more likely it is that you'll find people who are also interested and will help you build it, even if it's just by letting you bounce your ideas off them.

You can not work in a vacuum. Get your idea out as fast as possible and get feedback as early as possible.

If you're talking the 3D type WoW MMO that everybody seems to think they can improve then you'll need a team of 40+ people to start, including highly experienced game logic programmers/designers, graphic designers, network admins, testers, etc. It's far from a small or casual undertaking.

Start with a very light skinned down version of your game that you can make yourself and develop it from there. Use open source libraries and resources as much as possible so you're not reinventing the wheel at every turn. If you start to make it big then you'll be able to afford rebuilding your standin work, but if you spend 50 weeks making all the different kinds of plants you need, and that puts you only 20% of the way done with a beta launch, then you'll get nowhere in a hurry because you'll lose all your inertia.

---
Tags: mmo, game-industry, marketing
---


# Question
Title: What are the code structures for storyline based game?
I am curious about how storyline-based games are written.

For example: if the character done Event A, then he meets an NPC and result in Event B.

On the other hand: if the character didn't do Event A, then he meets an NPC and result in Event C.

From the code structure that I've thought up, the NPC should be an object of a class, and there should be a status variable that mark if character have done Event A or not. However, what if there's thousand of similar type of Event as Event A? How'd I handle huge, complex storyline game in coding?

I just want to know exactly how the trick was done to keep in check of what Events have happened.

Another thing that I'm curious about is how Event is kept in. An object? or just a function?

For example: Event A might have some flashy effect played in non-fmv ,while maybe Event B is an fmv, and Event C might be a battle.

and there may be variety of them. Therefore, how would I handle variety of Events with a consistence method? or maybe, at the very least, contain them in a consistence way (function? or Object?) I just want to know how the trick was done.

# Answer
> 3 votes
Your question is very similar to mine and I think the answers here may help you understand.

Basically you use game states and have the npc run a switch on the current state.

# Answer
> 3 votes
In the past I used bit fields to keep track of quests/events which a player had experienced. I then had the (ie) NPC do a check against the player's set of acquired flags and respond accordingly.

One advantage is that you can encode a tremendous amount of flags in a small structure. Another was that multiple, independent story lines could be encoded in a few separate variables.

One disadvantage was that I was only able to encode pass/fail style results.

http://www.nwnlexicon.com/compiled/primer.bitwiseoperators.html talks about this exact sort of thing and might be helpful. The logic of story line direction is then controlled by the events on locations/characters.

I really like the idea of a directed graph, but, I don't really think it's needed beyond a planning tool.

# Answer
> 1 votes
You likely will want to model this as a directed acyclic graph (or DAG), a logical, traversable structure consisting of nodes representing your story events or points at which the story branches.

Pros:

* You have the perfect structure with which to model complexity and branching. In fact, a tree is just a special type of graph, but while a tree might work for your game, a graph will be better as it will allow you to come to "nexus" points in your story (eg. the end of a chapter) where all prior story branches come together, and a new set of choices begin.
* A graph is easy to visualise on paper or in your head. Simply construct your story as a branching/remerging sequence of nodes.
* There are many useful algorithms for graphs, allowing you to do many cool (but advanced) things with your story graph.
* Using a DAG, as long as you mark a node as traversed each time you finish the relevant part of the story, you will not be able to go back to an earlier point in the story.

Cons:

* You'll need to figure out how to use graphs.
* You'll need to get yourself a suitable graph library like JGraphT, Boost, or LEDA depending on what is available for your language (Java and C++ are the traditional "academic's languages" so most of the good ones will be found in these) or write your own simple implementation.

PS. I refer above to graph algorithm libraries, not graph drawing / "graphing" libraries. The former provide an abstract way of constructing a topology (which is what you want) vs the former which provide different ways to draw you graph -- which may prove useful for your own visualisation but is not going to help your game to traverse its story as the player progresses.

PPS. It is possible to use a directed *cyclic* graph, meaning your player could go around in "story circles", this is how the "choose your own adventure" books sometimes work. But it's probably not the most desirable way.

---
Tags: game-design
---


# Question
Title: Rendering multiple textures on a terrain in XNA / C#
I am working on a terrain in XNA/C#. My intention is to be able to render multiple textures on the ground across the terrain. However, all tutorials like this are only capable of doing it with about 3-4 textures.

My idea is currently that I create a texture map in TGA that has different colors (RGBA) where each color represent a particular texture. The amount of Alpha in the color describes how much alpha the vertex on the position should have. And there would be a base texture.

However, I am a newbie in this area so I really need some getting started guides. So far I've managed to found none. All tutorials and resources are limited in terms of how many textures they support even though all modern games have many.

My game is an RTS, and having played a lot RTS games, I've noticed they all support lots of textures across the terrain. For example, the world editor for Command & Conquer 3 allows you to place any amount of any texture anywhere.

# Answer
First, I want to point out that the approach you linked to is capable of doing it with much more than 4 textures. In a SM 3 shader, you have 16 texture registers. You can use all of those registers if you want. Riemer's method just happens to pass 4 weighted values for textures from the vertex shader to the pixel shader. You could choose to pass 8 or 12 or whatever.

That said, as Andrew has pointed out, you probably don't want to just start using 12 textures for every part of your terrain.

Whatever method you choose, you're going to want to break your terrain down into chunks (see below).

Start by reading about texture splatting.

A gamedev paper explaining (the relatively simple) concept is here.

It has some drawbacks, but it works for World of Warcraft, and I suspect it will for you too.

It really depends what you're trying to achieve.

To permit the use of many different textures across the terrain, typically you want to split the terrain into chunks, and then assign texture information to each chunk to be drawn.

Below is a terrain split linearly into chunks. However, a common approach is to use a quadtree, so that chunks vary in size with distance.

If you want to draw decal textures over top of the terrain (e.g. blood splatter), you might need to draw a second terrain pass that only draws the transparent decals.

If you're curious about more advanced techniques, you can read about the Frostbite 1 engine's approach to procedural texture splatting here: http://publications.dice.se/attachments/Chapter5-Andersson-Terrain\_Rendering\_in\_Frostbite.pdf
> 3 votes

# Answer
First of all, allow me to poke some holes in your suggested method for expanding on that method:

First of all, you have a maximum of 16 texture samplers to use (ps\_3\_0 registers). So that is the limit of the expandability of the method you linked.

Second of all, each texture sampler in use will add to the texture bandwidth usage of your shader. (You may be able to mitigate this with conditionals in your shader - but I will leave you to do the experiment to see if it actually works.)

Finally, if you embed your "what texture to use" data in a texture, rather than as vertex data (as the tutorial you linked does), then you use up an available texture slot.

So, what are these games doing? I am going to take an educated guess:

First of all, they are probably using a multi-texturing technique similar to the one described in your link. They are possibly doing some tricks with this, for example: using different texture resolutions for detail and scrottox layers.

It also seems (I've been skimming this PDF) that their map builder is automatically chopping up the terrain mesh to allow different sections to use different textures, providing they are in different parts of the map. Thus increasing the number of available textures by increasing the number of batches rather than the number of samplers used (which seems like it would be better for performance).

I must admit - I am not sure how they're getting sharp edges in places - like the roads, while having blended edges elsewhere. But apparently roads are baked into the terrain texture somehow.

And finally, they are possibly also using *decals* to add fine detail to the map.
> 2 votes

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


# Question
Title: Should the game host be the authority, or another dumb client?
When designing a networked multiplayer-game where one player hosts and others connect, there are two strategies I'm aware of:

* **Have the host-player's game be the authority**, with all other players as dumb-clients trying to catch up with the current game-state. In the code, there will have to be lots of special cases, depending on if the current player is the host or not.
* **Make the host a dumb-client** like everyone else by running a hidden dedicated server on another thread. The dedicated-server will be the authority, and the host will connect to it like everyone else (through localhost).

What are the advantages/disadvantages of each of these? Which is used most often (or does it vary by game type/size)?

# Answer
The dumb-client approach is best from a pure design point of view- it heavily limits the amount of different code you need between host and clients, and allows the server to run asynchronously. The downside is that the host's machine requires extra resources- but I guess it always did.
> 13 votes

# Answer
Between these two options the dumb-client approach is certainly best for the reasons DeadMG mentions.

There is another option which is make every client an authority, it has the advantage of the dumb-client that all peers share the same code. The other advantage is that it might be a lot more fair if you set the right rules because no one has the 0-lag-to-server advantage.

This can ofcourse be rather tricky to implement depending on the game type. Your protocol will have to deal with solving conflicts between peers, probably using some kind of ownership scheme. Leaving only the conflicts where 2 peers claim ownership of the same game object.

Googling Peer-2-Peer multiplayer protocols might give you some more details about this approach.
> 8 votes

---
Tags: game-design, networking, multiplayer
---


title: Properties of good RTS level design?

text:
# Question
Title: Properties of good RTS level design?
I saw the general level design question but not much of it applies to building good solid levels for RTS games. Where can i find information on rules and mechanics of RTS level design?

# Answer
> 7 votes
Balance (usually symmetry) so that you don't get an unfair advantage by a random spawn point

Allied to this is having a big enough map with enough different start points so that there is an element of FUD at the beginning of the game: 'Where is he?', and the chance to use different strategies such as redeploying bases. It is fine to have a couple of football pitch type maps to learn the game but the whole fog of war/element of surprise is key to RTS games; it rewards reconnaissance and builds suspense.

Defensible positions. Narrow passes, bridges that you can take and hold

Some goal in the no man's land that encourages you to come out of your base to seize the initiative such as taking the high ground, capturing buildings, controlling resources, gaining technology.

---

Here is an interview with a professional RTS level designer, excerpted from the book Game Level Design By Edward Byrne:

http://books.google.com/books?id=iX3oWHNf9hMC&lpg=PP1&pg=PA166#v=onepage&q&f=false

# Answer
> 4 votes
Symmetry is good for balance but I have two things to add:

* If you make the different sides of map symmetrical, do this with things that matter for gameplay (such as size and passability of areas) but try to vary the different sides visually where possible (such as different textures and props, using mountains as blockade on one side but buildings on the other). This brings more variety in the map to make it more interesting.
* Or to take it further, you could try making maps not symmetrical, while still maintaining the balance by compensating disadvantages with advantages. This is much harder though.

Oh, and sometimes people want to play maps that are fun, and not necessarily balanced at all. It can be interesting to play against a friend "with one hand strapped to your back".

# Answer
> 1 votes
http://theussner.wordpress.com/2010/09/13/rts-level-design-the-layout-part-1/#comment-28

This link is to a German (in English) game designer's blog. He has only done part 1 so far but makes some good points as to how RTS map's should be conceptualized. Leaving some comments will no doubt encourage him to complete the series on RTS map design.

# Answer
> 0 votes
I actually disagree with the 100% even game.

Games such as travian and tribalwars demonstrate a bad example of unevenness. Your position almost completely determines whether you will live or die in the first few weeks.

However if your game is just a team vs team game, which will only go for half an hour to an hour, then you will find that having a randomly generated situation is sometimes quite fun (although it must not be too unbalanced).

The "Pro's" at the game, will be excited by the idea of winning even if it was unfair for them, and when it is easier for them, well big deal, its only half an hour.

The not noobs or pro's people will thrive when advantaged, and learn more when disadvantaged.

And the noobs will enjoy a higher success when it is an easier situation, but will have the excuse of "well i'm still learning" when they get flogged.

This works especially well, when people are matched up to someone of a similar "Level" or "Experience"

...

Just my 2c

---
Tags: rts, level-design
---


# Question
Title: How to efficiently organise all object in a large space
I've just about started with a project I've had in mind for ages. I don't quite know how to start such big projects (bigger than Pong, anyway), so I thought I would get started by making a basic organization.

Now, in games like Freelancer and X feature large, open spaces. I ma aware that these have to be organised, to ensure collision testing don't happen continuously anywhere but only where the player can see it.

I thought first about a general scene graph, I am familiar with those, but it would just have almost all objects directly in the root node. The next idea was a Quad/Octree, but the objects are not quite static, and I don't know if it would make sense if you have to change the tree's organisation every second frame.

So, how is this done in real games? I'm using C# with XNA, if that matters, and would like to run the game on the XBox as well.

# Answer
> 0 votes
Given the minimal information in the question, there is no general answer to that.

Except: *Real* games use engines that implement features as scene-graphs and proper data structures for collsion-detection and -optimizations, rendering, network, input, serializing and much more.

The idea is to write a game, not an engine.

Unity3D is such an engine for C#.

---
Tags: collision-detection, scene-graph, octree
---


title: Marching Cubes - Legalities?

text:
# Question
Title: Marching Cubes - Legalities?
I know this isn't a "Is this legal" website, but because Marching Cubes is definitely a large subject in game development, and isn't really about a specific graphic/item, it would pass...

To the point!

Does anyone know whether Marching Cubes is allowed in a commercial game? If so is there anything i must do? Credit to someone/company etc?

Cheers.

# Answer
Wikipedia says:

> This patent expired in 2005, and it is now legal for the graphics community to use it without royalties since more than 17 years have passed from its issue date (December 1, 1987\[2\]).

Still it's always a good idea to double-check with your lawyer.
> 14 votes

---
Tags: legal
---


# Question
Title: Simple, casual open source OpenGL games to implement other things in
I am looking for a simple casual game (open source) done in openGL. I need it to implement communication component i build this is not for learning opengl and to implement some other stuff into it. Where can I find one? (I am using C++) Thanks

# Answer
I don't think reading another game's source code in isolation is going to help you learn much; there's a pretty severe lack of context in most code, so you won't know why particular programming design or implementation decisions were made. You can very easily pick up bad habits or the wrong idea.

That said, a similar question has been asked here before. Also, here is a list of open source games from Wikipedia, and this website is dedicated to open-source game development news and you might be able to find some examples there. Beyond that, it's a little difficult to provide what you've asked for since you haven't offered very many guidelines as to what you're trying to learn.
> 4 votes

# Answer
Check out this question. Not only C++, but you still should be able to get some ideas.
> 0 votes

---
Tags: opengl, c++, open-source, casual-games
---


# Question
Title: Getting started with cross-platform game development
I am looking for a starting place to develop a crossplatform OpenGL game that runs on Mac, PC and potentially Linux. The difficulty is that I don't want to use an existing graphics library.

I've done a lot of work with OpenGL in C++ for Windows. I have never developed anything for Mac. I plan to develop most of the Windows game and leave my project open with abstraction so that I can later implement Mac-specific code.

Is there anything that works radically different in Mac and Linux than in Windows? With Windows for example, I use DirectInput and XInput to capture controllers and keyboard, window messages to capture mouse and typing. Where can I find some type of "translation guide"? Also, do I still need to consider endianness?

How can I design my project so that I can load it up in Visual Studio 2008 and easily compile it in OSX and Linux IDEs? Since I own Visual Studio, I'd like to use that for my Windows development, rather than switch to a cross-platform IDE.

# Answer
I don't know if this worth to be an answer but as it's too long to be a comment... here are some informations that might help you.

* You should take a look at this small article.
It enumerates 10 rules to write cross-platform C/C++ code. And one idea that particularly pushed me to change my development organization, is that it would be more "optimized" (from his experience) to develop all platforms at the same time instead of porting to other platforms later.
So I decided to apply this idea (among others) with my game, and despite the fact that it was a bit long to configure the 3 operating systems to make them compile my code (and to feel good using them), it's now really easy to test each new version on the 3 platforms. All the others ideas in this article are indeed very interesting, but this one is the most important to me.
* As for the endianness question, as far as I know, it depends more of the processor architecture than of the operating system: Endianness and operating systems on architectures
> 3 votes

---
Tags: opengl, windows, cross-platform, linux, macos
---


# Question
Title: Isometric screen to 3D world coordinates efficiently
Been having a difficult time transforming 2D screen coordinates to 3D isometric space. This is the situation where I am working in 3D but I have an orthographic camera. Then my camera is positioned at (100, 200, 100), Where the xz plane is flat and y is up and down.

I've been able to get a sort of working solution, but I feel like there must be a better way.

Here's what I'm doing:

With my camera at (0, 1, 0) I can translate my screen coordinates directly to 3D coordinates by doing:

```
mouse2D.z = (( event.clientX / window.innerWidth ) * 2 - 1) * -(window.innerWidth /2);
mouse2D.x = (( event.clientY / window.innerHeight) * 2 + 1) * -(window.innerHeight);
mouse2D.y = 0;

```

Everything okay so far. Now when I change my camera back to (100, 200, 100) my 3D space has been rotated 45 degrees around the y axis and then rotated about 54 degrees around a vector Q that runs along the xz plane at a 45 degree angle between the positive z axis and the negative x axis.

So what I do to find the point is first rotate my point by 45 degrees using a matrix around the y axis. Now I'm close.

So then I rotate my point around the vector Q. But my point is closer to the origin than it should be, since the Y value is not 0 anymore. What I want is that after the rotation my Y value is 0. So now I exchange my X and Z coordinates of my rotated vector with the X and Z coordinates of my non-rotated vector. So basically I have my old vector but it's y value is at an appropriate rotated amount.

Now I use another matrix to rotate my point around the vector Q in the opposite direction, and I end up with the point where I clicked.

Is there a better way?

I feel like I must be missing something. Also my method isn't completely accurate. I feel like it's within 5-10 coordinates of where I click, maybe because of rounding from many calculations. Sorry for such a long question.

# Answer
I finally found the answer.

https://stackoverflow.com/questions/912418/unprojecting-an-on-screen-point-back-to-an-isometrically-projected-world
> 4 votes

---
Tags: 3d, coordinates, isometric, screen
---