title: Save-security with MD5 hash

text:
# Question
Title: Save-security with MD5 hash
I'm working on a flash game that saves your progress locally. These saves can easily be hacked. My solution is to add an md5 hash of all the variables saved into the save file itself. When loading the save, the game would check if the hash is valid.

Is this a good solution? Are there better solutions?

# Answer
The way you have it described, somebody hacking a save file would just need to construct an MD5 hash of the save file values in order to bypass this measure. You need to add one thing in order for this to even really be worthwhile: a secret block of arbitrary data that's added to what you're hashing (both when creating the save and when validating it on restore). The mechanism won't be uncrackable or anything at that point, but it'll be resistant to medium-casual tampering. If you can avoid having the data block be easily extractable from your runtime files using a hex editor, that'll add another notch.

If you want people to actually not be able to hack your saves, you cannot perform local saves at all. You cannot trust the client because the client is in the hands of the enemy.
> 27 votes

# Answer
If this is not an online tracked competitive type game:

Let em hack away man. You can spend way too much energy on things like this when people who will play the game, will just play the game. Those who want to hack it will never really want to play it, they just want to hack it.

If it is an online competitive type game:

All you have to do is store the hashes on a server some where with their login information. If the hash from their save file is not valid, then their game is not valid.. Start over, or revert, or whatever :)

This is fairly basic but there again, we are talking about games, not bank accounts and such.. And always remember.. hobbyist or professional gamer developer, there are Hundreds of people out there who are going to try and hack your games. Put in enough effort to try and preserve the enjoyment of the game for those who are going to play by the game's rules, and thats about it.
> 12 votes

# Answer
This is not a good solution, since all the values hashed are in the save file.

If the attacker twiddles something, they just have to recompute the hash and store that in the save file too...

Saving things locally without any online state tracking is fundamentally non-securable.

You need an element that is on the server such as HMACing with a key that only the server stores.

This will not guard against an active attack where the attacker impersonates or otherwise piggybacks a live session however.

I know people who delight in hacking Flash games btw.
> 4 votes

---
Tags: logic, security, anti-cheat, savegame
---


# Question
Title: Who owns the intellectual property to Fragile Allegiance?
Fragile Allegiance was developed by Gremlin Interactive, which was later acquired by Infogrames (Atari). I couldn't find any details of the acquisition though.

The only interesting thing I have found online is that the owner of the registered trademark Fragile Allegiance is Interplay, who published Fragile Allegiance. However, the only copyright note I've found was in one installation .ini file, claiming it for Gremlin.

~~What are the common business practices when it comes to old, unused IPs? What do publishers/developers actually need to legally claim an intellectual property? Does anyone have an experience with contacting big publishers with copyright/IP inquiries?~~

Related legal question.

# Answer
http://www.atari.com/publish would be where to contact Atari (sorry, you do need to login using an Atari account).
> 3 votes

---
Tags: legal, copyright
---


# Question
Title: Whats the point of all these Surface Formats
I am relevantly new to Graphics Programming. I have written some basic games in xna in the past but I am trying to understand what the point of all these surface formats is. For instance Xna and DDS support the standard RGBA (8bpp). Why does one need 32 bpp or even stranger combinations of bits per channel like Rg32. Isn't it enough to have the standard DXn, RGBA, and HDR formats?

# Answer
You think XNA has a lot of surface formats? Boy, you ain't seen nothing yet.

Joking aside, I suspect the reason has to do with a combination of legacy/backwards compatibility and flexibility.

Obviously, once a surface format is introduced it needs to be supported forward for some time, or the entire API takes a backwards compatibility hit. So there are probably a few surface formats that float about just due to that reason alone.

But the bigger reason is the flexibility that is afforded to developers by having many surface format options to choose from -- this allows developers to do things like use as few bits as possible for a particular channel, or as few channels as possible for scenarios where optimizing space is an important consideration. It allows for the possibility of expanding to very large bit-widths when broad ranges of color data are going to be required (for example, for HDR, as you mentioned). Some formats exist for relatively specialized (but very common, possibly performance critical graphics operations) tasks -- the `NormalizedByte2` format, for example, is commonly used in bump-map related operations (per the documentation).

Some of the strange looking formats can be useful for non-graphics operations, too, like general GPU computation where you may only need two channels of input data (and thus, why waste space on the third when that video memory could be put to better use -- such as allowing *more* of the two-channel data you're trying to process?)

Having a variety of formats also allows the developer to communicate to the GPU how the data will be arranged and used (this is why the DXGI format list is so big, because it not only includes bit-width variations, but some type information as well, such as whether the values will be signed or unsigned), which in turn can allow the GPU to optimize its buffer layouts for maximum pipeline throughput.

Finally, some of the formats are restricted in where and when they can be used, which necessitates a list that may seem sprawling at first, but is actually relatively compact for any given scenario. Relatively few formats can be used for a depth buffer, for example.
> 15 votes

---
Tags: xna, image, file-format
---


title: Good books for MMORPG design?

text:
# Question
Title: Good books for MMORPG design?
What is the recommended reading list for a very experienced s/w developer, with no MMORPG experience, who wants to design an MMORPG?

# Answer
> 12 votes
Hanging around Terra Nova is also probably not a terrible idea.

---
Tags: mmo, books
---


# Question
Title: Can and should a game design be patented?
I have an idea for a game that I want to develop and I feel is unique, and I'm wondering if I should patent it. I read on the web that games can be patented, but just because it can be done doesn't mean that it makes sense to do it.

I actually don't really want patent it (it's expensive, a hassle and I don't believe in patenting of ideas... unless it's something truly revolutionary). However, I'm concerned a bigger company could come along, with more experienced game designers and developers and steal the idea.

# Answer
It is often said that game ideas are a dime a dozen, but that's not true -- they're probably cheaper than that. An idea alone is essentially worthless, what matters is that you have the skill or capability to flesh that idea out into a design, and then execute that design.

Professional game developers do not trawl the internet looking for ideas to "steal" -- any one individual in a company has at least a few ideas they eventually would love to develop and most companies have many people, so there is never likely to be a shortage of game ideas. Furthermore, companies do not want to get themselves into even *potential* legal hot water by doing what you're worried about -- it's part of the reason most studios simply bin unsolicited "game design documents" (and believe me, we do get these in the mail quite often) without reading them as a general policy.

The chance that your idea is truly unique is pretty slim. But that doesn't mean it's a bad idea, just that you probably do not need to spend a lot of time or money patenting it. I would instead suggest that you spend that time and money developing it into a playable game.
> 44 votes

# Answer
(IANAL)

**Patents**, for the most part, do not apply to ideas but rather to specific implementations of them. You may be able to get a patent for a specific process or methodology that your game uses, but this is a rather poorly-defined area with software. Also, patents require disclosing all of your information. Coca-cola's recipe is not patented because that would involve divulging their secret recipe.

**Copyright** tends to be more applicable to code, but it is very loose in terms of what it protects. Two pieces of software can be frighteningly similar yet not infringe upon each other.

What you want to do is keep it a **trade secret**. Don't tell anyone about it who doesn't need to know about it. Make everyone who you DO tell about it sign a non-disclosure agreement. If you're worried about someone independently arriving at your idea and beating you to market with it...well, you're out of luck. There is no protection for that.
> 10 votes

# Answer
In short? Yes, you probably can patent the methodology or process. I'm not a lawyer, however.
Would you want to? No.
Should you be worried of large companies stealing your idea? No. They have large teams who are trained to develop new game concepts. I seriously doubt they would go around the internet looking for concepts.

If you want to be worried of anything (which is stupid), then think of hobby developers. They're the ones who will be playing your games and might take your idea. But who cares if they do? Ideas are so common, they're pretty much worthless.

I've had a massive amount of them. Some of them have actually been games which I had never heard about. So the chance of your idea being unique is tiny.
> 1 votes

# Answer
Patent are useful for laboratories when they spend a lot of money finding solutions which need a lot of scientific work: for example, finding an efficient molecule to develop a drug that treats a certain disease, requires work, while making that molecule is just a matter of chemistry.

On the other hand, a software idea just requires the work to implement it, something that is just plain different.

In one case, it requires work to find a solution, in the second it requires work to make it work.

Patent protects research that finds stuff, NOT the people who make them. The protection for people who makes stuff is called copyright, which is completely different. This way, patents are much much rarer than copyrights.

The problem with patents is this: They are over used anyways, because there will always be a debate about the expertise necessary to validate something that can be patented. Just look at all those numbers that appear when you start up adobe reader: it didn't prevent Google, Foxit and other application to write their own PDF converter. Also TeX seems to be able to produce equal if not superior quality documents.
> 0 votes

---
Tags: game-design, legal, business
---


# Question
Title: 3d environments and managing them on iOS
I would like to start learning 3d game development and currently only develop 2d games.

A few basic questions I am interested in are:

What is used to create the 3d environments? Are they all done in e.g. Maya, Lightwave, 3d modeling software?

What is the output format for these models and how are they manipulated in iOS? Is it all done using openGL(GL ES on iOS)?

e.g a monster needs to be spawned in the game world. What coordinates are used?

Are the concepts the same as 2d in terms of collision on the coordinates and movement on the coordinates of the game world?

How are 3d games managed in iOS on the low available memory. (e.g. FPS games)

Lastly, Can someone please recommend a good book that is up to date and can be applied to todays techniques.

Thanks

# Answer
> 2 votes
To answer some:

Yes, modelling is being done in a modelling software. Tho you can generate meshes programatically too. Or you can write the model files using a text editor :) So basically you use some 3d software like Max, Maya or Blender.

The output depends on the software used. E.g. Max has the .max format. But usually you can export your models into some common formats like .obj. If you want to write a 3d game engine from the ground up, then you'd have to write the code that loads these formats. It's quite tedious, but that's the reason people use libraries for these (or complete game engines...).

World coordinates are used for spawning things into the world :) Check out some books on 3d.

I'd recommend checking out some available 3d engines, to try things out and understand the concepts better. Ogre or Unity is a good start I think. I can't recommend any books, there're thousands on this topics regarding your questions (most of them are rubbish tho). It's like you ask us to recommend you a book on mathematics. Be more specific.

---
Tags: 3d, coordinates
---


title: Triangle - Rectangle Intersection in 2D

text:
# Question
Title: Triangle - Rectangle Intersection in 2D
I had previously asked this for 3D but now I changed my strategy and would like to do the intersection in 2D.

The Rectangle is axis aligned and will always be in a fixed position, and has a constant shape and size, basically I want to clip the red areas of the triangles that extend outside the bounds of the rectangle. The triangles could be in any position, shape or size, I my code I have a loop where I check the triangles one by one, however I am still clueless about the math.

I have identified 5 cases of triangle rectangle intersection as shown here.

How do I find the intersection points of the triangle and the rectangle?

# Answer
> 8 votes
The Sutherland-Hodgman polygon clipping algorithm should work just fine for triangle vs. rectangle clipping. You'll find some more information about clipping algorithms here. Or just search for "Sutherland Hodgman clipping".

# Answer
> 1 votes
I think CGAL i too robust for such simple task. And Sutherland Hodgman clipping is usefull, when you have general polygon. But you have axis aligned box and you should make use of it.

So my opinion:

First case: Triangle and box are intersecting. You can figure it out by line-line intersection test (for example this: http://mathworld.wolfram.com/Line-LineIntersection.html but you can google it in many ways - also look at EDIT2 at the end of this answer). You make line from every edge of box and every edge of triangle. Then you find intersection of all combinations (there are 12 cases \<- 3 (triangle) x 4 (box) edges).

If you find intersection point (IP), test, if IP lies between two vertices of triangle or somewhere else on line (created from triangle edge). If IP lies between vertices, then test, if IP's x and y coordinates lie in box x and y intervals (it's axis aligned) - it's green case on picture. If IP doesn't lie in both of it's intervals, then it's red case on picture.

After this test, you should have several vertices, which define your new polygon created from triangle.

//EDIT: Oh. I forget, you have to take also every vertex from triangle for your new polygon, which lies in box (on picture there are two such vertices).

If no edge-edge intersection is found, you have to check two other cases:

Second case: Whole rectangle lies in triangle - your new points from triangle are just vertices of box.

Third case: Whole triangle is in box. Take original triangle as result.

I hope, this can work. It's not tested. Maybe you can use some heuristic and avoid of testing all possible edge-edge combinations.

//EDIT2: You should also make use of axis aligned box in line-line intersection test - just find y coordinate with given x constant (in case of vertical box edge) or find x coordinate with given y constant (in case of horizontal edge).

# Answer
> 0 votes
You may find the answer to your question here on Stack Overflow.

They suggest using CGAL which is a C++ library for Geometric Algorithms. You could also use C++'s Boost.Geometry for a solution as well.

---
Tags: 2d, intersection, actionscript
---


title: 2d tank movement and turret solution

text:
# Question
Title: 2d tank movement and turret solution
I'm making a simple top-down tank game on the ipad where the user controls the movement of the tank with the left "joystick" and the rotation of the turret with the right one. I've spent several hours just trying to get it to work decently but now I turn to the pros :)

I have two referencial objects, one for the movement and one for the rotation. The referencial objects always stay max two units away from the tank and I use them to tell the tank in what direction to move. I chose this approach to decouple movement and rotational behaviour from the raw input of the joysticks, I believe this will make it simpler to implement whatever behaviour I want for the tank.

My problem is 1; the turret rotates the long way to the target. With this I mean that the target can be -5 degrees away in rotation and still it rotates 355 degrees instead of -5 degrees. I can't figure out why. The other problem is with the movement. It just doesn't feel right to have the tank turn while moving. I'd like to have a solution that would work as well for the AI as for the player. A blackbox function for the movement where the player only specifies in what direction it should move and it moves there under the constraints that are imposed on it.

I am using the standard joystick class found in the Unity iPhone package.

This is the code I'm using for the movement:

```
public class TankFollow : MonoBehaviour {
//Check angle difference and turn accordingly

public GameObject followPoint;
public float speed;
public float turningSpeed;

void Update()
{
    transform.position = Vector3.Slerp(transform.position, followPoint.transform.position, speed * Time.deltaTime);
    //Calculate angle
    var forwardA = transform.forward;
    var forwardB = (followPoint.transform.position - transform.position);

    var angleA = Mathf.Atan2(forwardA.x, forwardA.z) * Mathf.Rad2Deg;
    var angleB = Mathf.Atan2(forwardB.x, forwardB.z) * Mathf.Rad2Deg;

    var angleDiff = Mathf.DeltaAngle(angleA, angleB);
    //print(angleDiff.ToString());
    if (angleDiff > 5) {
        //Rotate to
        transform.Rotate(new Vector3(0, (-turningSpeed * Time.deltaTime),0));
        //transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y + adjustment, transform.rotation.z, transform.rotation.w);

    }
    else if (angleDiff < 5) {
        transform.Rotate(new Vector3(0, (turningSpeed * Time.deltaTime),0));
        //transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y + adjustment, transform.rotation.z, transform.rotation.w);

    }
    else {

    }
    transform.position = new Vector3(transform.position.x, 0, transform.position.z);
}

```

}

And this is the code I'm using to rotate the turret:

```
    void LookAt()
{

    var forwardA = -transform.right;
    var forwardB = (toLookAt.transform.position - transform.position);

    var angleA = Mathf.Atan2(forwardA.x, forwardA.z) * Mathf.Rad2Deg;
    var angleB = Mathf.Atan2(forwardB.x, forwardB.z) * Mathf.Rad2Deg;

    var angleDiff = Mathf.DeltaAngle(angleA, angleB);
    //print(angleDiff.ToString());
    if (angleDiff - 180 > 1) {
        //Rotate to
        transform.Rotate(new Vector3(0, (turretSpeed * Time.deltaTime),0));
        //transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y + adjustment, transform.rotation.z, transform.rotation.w);

    }
    else if (angleDiff - 180 < -1) {
        transform.Rotate(new Vector3(0, (-turretSpeed * Time.deltaTime),0));
        //transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y + adjustment, transform.rotation.z, transform.rotation.w);
        print((angleDiff - 180).ToString());
    }
    else {

    }
}

```

Since I want the turret reference point to turn in relation to the tank (when you rotate the body, the turret should follow and not stay locked on since it makes it impossible to control when you've got two thumbs to work with), I've made the TurretFollowPoint a child of the Turret object, which in turn is a child of the body. I'm thinking that I'm making it too difficult for myself with the reference points but I'm imagining that it's a good idea. Please be honest about this point.

So I'll be grateful for any help I can get!

I'm using Unity3d iPhone. Thanks!

# Answer
> 2 votes
If the turret is turning the wrong way try using Mathf.MoveTowardsAngle: http://unity3d.com/support/documentation/ScriptReference/Mathf.MoveTowardsAngle.html

Seems like you could do something like below to get the desired result:

```
var angle : float = Mathf.MoveTowardsAngle(angleA, angleB, turretSpeed * Time.deltaTime);
transform.eulerAngles = Vector3(0, angle, 0);

```

---
Tags: unity, vector, movement, rotation
---


# Question
Title: Making organic 2D tilemaps for tile based games
So I have always wondered how one makes a nice (not so squarish) 2d tile map, is it possible? all games now days I think use textured polygons...but my game engine (and engine) doesn't support that to my knowledge. But it does support nice TMX files generated by mapeditor.org's Tiled Map Editor. Though in my game I want nice twisting and turning caverns to traverse ... I was wondering some ideas on such a process... is it in the art style? The type of tile engine? both? So what are some common techniques?

# Answer
> 9 votes
The quick answer is: Both.

The human brain is very good at recognizing axis aligned repeating patterns.. Very very good.. however, rotate a textures repeating edges 30-60 degrees and you will find it hides the repeating edges very well. Now this is more of a discussion for 3D environments than 2D but the same basic principals apply. If you can make it so your the repeating edges of your Texture are NOT the same edges as the repeating edges of your tiles, it will make them a bit nicer.

Another way that this is accomplished in the realm of 3D is multi-texturing. Now this is a much easier thing to do in a 2D environment. Adding in multiple 'tile layers' that render on top of each other would achieve a more varied set of tiles with out requiring a significant amount of new tiles to be created. You would want around 5 layers or so total, 3 layers that are completely behind the player and then 2-3 layers that would render on top of the player, or objects in the scene in general.

The farthest back layer would be the most repetitious and would be the generic surface you are walking on (I am assuming from what your question said that you are a top down or angle down view of the environment like Diablo or so). The next layer would still be commonly repeating but would make each area a bit 'different'. This could be collections of loose rubble, piles of bones, monster tracks and things like this that would be on top of the floor. The third background layer may or may not be needed and would be mostly for specialized tile sets, like a trickle of water or the like.

The foreground layers would be used to add a bit more uniqueness to your view. You could have a character walk behind hanging lamps down the corridors, cobwebs that hint at a large number of spiders in the area or even a completely obscuring object such as a roof brace or the like.

Now the answer is both in that as soon as you have adapted your tile engine to allow multiple layers like this, you will need the artwork to fill both of the layers.. And the key for the artist will to be to create the basic patters and the unique patterns that can be used together in multiple combinations and still look good (and not completely suck up all the memory you have to work with :))

EDIT: From the comment given this gives an entirely new approach, hehe. What is said above still applies, but since we are dealing with large heights (perception wise if we are flying :)) you might benefit from a bit of parallax scrolling (where the tile layers do not scroll at the same rate as each other). This would potentially give you the ability to do deep crevices, or a break through the cloudy sky you are flying through to see the world below. As for the complication implied, its really just a repetition of what you are currently doing.. Instead of rendering a single set of tiles at a time you will do it a few times.. It should not be too much of a stretch from where it sounds like your current game and engine are :)

Anywho, hope this was enough of an answer to help you progress or at the least have new questions to ask.

Enjoy!

---
Tags: tiles, maps
---


# Question
Title: Adding objects to the environment at timed intervals
I am using an `ArrayList` to handle objects and at each interval of 120 frames, I am adding a new object of the same type at a random location along the z-axis of 60. The problem is, it doesn't add just 1. It depends on how many are in the list. If I kill the Fox before the time interval when one is supposed to spawn comes, then no Fox will be spawned. If I don't kill any foxes, it grows exponentially. I only want one Fox to be added every 120 frames. This problem never happened before when I created new ones and added them to the environment. Any insights?

Here is my code:

```
/**** FOX CLASS ****/
import env3d.EnvObject;
import java.util.ArrayList;

public class Fox extends Creature
{
    private int frame = 0;
    public Fox(double x, double y, double z)
    {
        super(x, y, z);

        // Must use the mutator as the fields have private access
        // in the parent class
        setTexture("models/fox/fox.png");
        setModel("models/fox/fox.obj");

        setScale(1.4);
    }

    public void move(ArrayList<Creature> creatures, ArrayList<Creature> dead_creatures, ArrayList<Creature> new_creatures)
    {
        frame++;
        setX(getX()-0.2);
        setRotateY(270);

        if (frame > 120) {
            Fox f = new Fox(60, 1, (int)(Math.random()*28)+1);
            new_creatures.add(f);
            frame = 0;
        }

        for (Creature c : creatures) {
            if (this.distance(c) < this.getScale()+c.getScale() && c instanceof Tux) {
                    dead_creatures.add(c);
            }
        }

        for (Creature c : creatures) {
            if (c.getX() < 1 && c instanceof Fox) {
                dead_creatures.add(c);
            }
        }
    }
}

import env3d.Env;
import java.util.ArrayList;
import org.lwjgl.input.Keyboard;

/**
 * A predator and prey simulation.  Fox is the predator and Tux is the prey.
 */
public class Game
{
    private Env env;
    private boolean finished;
    private ArrayList<Creature> creatures;
    private KingTux king;
    private Snowball ball;
    private int tuxcounter;
    private int kills;

    /**
     * Constructor for the Game class. It sets up the foxes and tuxes.
     */
    public Game()
    {
        // we use a separate ArrayList to keep track of each animal.
        // our room is 50 x 50.
        creatures = new ArrayList<Creature>();

        for (int i = 0; i < 10; i++) {
            creatures.add(new Tux((int)(Math.random()*10)+1, 1, (int)(Math.random()*28)+1));
        }

        for (int i = 0; i < 1; i++) {
            creatures.add(new Fox(60, 1, (int)(Math.random()*28)+1));
        }

        king = new KingTux(25, 1, 35);

        ball = new Snowball(-400, -400, -400);
    }

    /**
     * Play the game
     */
    public void play()
    {

        finished = false;

        // Create the new environment.  Must be done in the same
        // method as the game loop
        env = new Env();

        // Make the room 50 x 50.
        env.setRoom(new Room());

        // Add all the animals into to the environment for display
        for (Creature c : creatures) {
            env.addObject(c);
        }

        for (Creature c : creatures) {
            if (c instanceof Tux) {
                tuxcounter++;
            }
        }

        env.addObject(king);
        env.addObject(ball);

        // Sets up the camera
        env.setCameraXYZ(30, 50, 55);
        env.setCameraPitch(-63);

        // Turn off the default controls
        env.setDefaultControl(false);

        // A list to keep track of dead tuxes.
        ArrayList<Creature> dead_creatures = new ArrayList<Creature>();
        ArrayList<Creature> new_creatures = new ArrayList<Creature>();

        // The main game loop
        while (!finished) {

            if (env.getKey() == 1 || tuxcounter == 0)  {
                finished = true;
            }

            env.setDisplayStr("Tuxes: " + tuxcounter, 15, 0);
            env.setDisplayStr("Kills: " + kills, 140, 0);

            processInput();

            ball.move();

            king.check();

            // Move each fox and tux.
            for (Creature c : creatures) {
                c.move(creatures, dead_creatures, new_creatures);
            }

            for (Creature c : creatures) {
                if (c.distance(ball) < c.getScale()+ball.getScale() && c instanceof Fox) {
                    dead_creatures.add(c);
                    ball.setX(-400);
                    ball.setY(-400);
                    ball.setZ(-400);
                    kills++;
                }
            }

            // Clean up of the dead tuxes.
            for (Creature c : dead_creatures) {
                if (c instanceof Tux) {
                    tuxcounter--;
                }
                env.removeObject(c);
                creatures.remove(c);
            }

            for (Creature c : new_creatures) {
                creatures.add(c);
                env.addObject(c);
            }

            // we clear the ArrayList for the next loop.  We could create a new one
            // every loop but that would be very inefficient.

            dead_creatures.clear();
            new_creatures.clear();

            // Update display
            env.advanceOneFrame();
        }

        // Just a little clean up
        env.exit();
    }

    private void processInput()
    {
        int keyDown = env.getKeyDown();
        int key = env.getKey();

        if (keyDown == 203) {
            king.setX(king.getX()-1);
        } else if (keyDown == 205) {
            king.setX(king.getX()+1);
        }

        if (ball.getX() <= -400 && key == Keyboard.KEY_S) {
            ball.setX(king.getX());
            ball.setY(king.getY());
            ball.setZ(king.getZ());
        }
    }

    /**
     * Main method to launch the program.
     */
    public static void main(String args[]) {
        (new Game()).play();
    }
}

/**** CREATURE CLASS ****/
/* (Parent class to Tux, Fox, and KingTux) */
import env3d.EnvObject;
import java.util.ArrayList;

abstract public class Creature extends EnvObject
{
    private int frame;
    private double rand;
    /**
     * Constructor for objects of class Creature
     */
    public Creature(double x, double y, double z)
    {
        setX(x);
        setY(y);
        setZ(z);
        setScale(1);
        rand = Math.random();
    }

    private void randomGenerator()
    {
        rand = Math.random();
    }

    public void move(ArrayList<Creature> creatures, ArrayList<Creature> dead_creatures, ArrayList<Creature> new_creatures)
    {
        frame++;
        if (frame > 12) {
            randomGenerator();
            frame = 0;
        }

//         if (rand < 0.25) {
//                 setX(getX()+0.3);
//                 setRotateY(90);
//         } else if (rand < 0.5) {
//                 setX(getX()-0.3);
//                 setRotateY(270);
//         } else if (rand < 0.75) {
//                 setZ(getZ()+0.3);
//                 setRotateY(0);
//         } else if (rand < 1) {
//                 setZ(getZ()-0.3);
//                 setRotateY(180);
//         }

        if (rand < 0.5) {
            setRotateY(getRotateY()-7);
        }   else if (rand < 1) {
            setRotateY(getRotateY()+7);
        }

        setX(getX()+Math.sin(Math.toRadians(getRotateY()))*0.5);
        setZ(getZ()+Math.cos(Math.toRadians(getRotateY()))*0.5);

        if (getX() < getScale()) setX(getScale());
        if (getX() > 50-getScale()) setX(50 - getScale());
        if (getZ() < getScale()) setZ(getScale());
        if (getZ() > 50-getScale()) setZ(50 - getScale());

        // The move method now handles collision detection
        if (this instanceof Fox) {
            for (Creature c : creatures) {
                if (c.distance(this) < c.getScale()+this.getScale() && c instanceof Tux) {
                    dead_creatures.add(c);
                }
            }
        }
    }
}

```

The rest of the classes are a bit trivial to this specific problem.

# Answer
> 2 votes
If I understand your code, your fox class is the one that spawns new fox objects inside the move method. By putting this logic in the move method, multiple fox instances are adding more foxes to the list. Also, if no foxes exist, this logic will never occur because the move method will not execute (no instances to call upon). Thus, if there are no more foxes (no fox objects are being updated) then foxes will not be spawned.

You should move this spawning code outside of the fox class. That way only one fox is added every 120 frames (no exponential growth) and a fox will always respawn, regardless of whether there are no more foxes.

Keep track of the frames and spawn foxes outside of this move method. Do not put it inside the fox class, make it independent of fox instances so that this logic is only at least and no more than once, regardless of the number of fox instances. That's the only reason why your seeing this erratic behavior. It's because you've got some game logic in the wrong place, making it dependent on whether there are fox instances being moved (updated) when this spawning logic should be independent and outside of the move method, and perhaps the fox class altogether.

# Answer
> 0 votes
It may be my lack of understanding the underlying objects here, but I think the definition of 'frame' is the cause of the problems.

You are incrementing the counter once per creature so the more creatures you have the faster new ones will spawn. This likely should be incremented before the call to move() instead of inside the call that happens once per creature.

If this isn't the case, please clarify in comments and I'll try again. :)

EDIT: This is the line that is the culprit; you are ++frame PER FOX, not per update loop as mentioned in the comments section:

```
public void move(ArrayList<Creature> creatures, ArrayList<Creature> dead_creatures, ArrayList<Creature> new_creatures)
{
    frame++;

```

This should be done in the loop that is calling move() or the like, not by the move method, unless this frame variable is, as suggested, part of the fox object itself. In that case, every fox has its own unique frame counter to spawn off of; that also gives you your exponential growth.

---
Tags: java
---


# Question
Title: What tool should I use for drawing 2D OpenGL shapes?
I'm working on a very simple OpenGL ES 2.0 game, and I'm not sure what tool to use to create the vertex data I need. My first thought was adobe illustrator, but I can't seem to find any info on how to convert an .ai file to vertices. I'm only going to be using very simple 2D shapes so I wonder if I need to use a 3d modelling program?

How is this typically done, when you are working with 2D non-sprite shapes?

# Answer
If shapes are really complicated, I would recommend 3D modelling software (for example Blender, which is freeware). When you will be loading data, you can just throw away one coordinate. You can for example use front orthogonal view and then discard z-coordinate.

Such software also allow to export data to some graphic format, like OBJ or PLY. There is a lot of loaders for them already written.
> 4 votes

# Answer
You could try importing files in the SVG file format. It's not super simple, but there are a fair number of tools that can output the format (such as Inkscape on Windows). The fog framework includes a SVG loader, and you can find a few other examples by poking around Google.
> 1 votes

# Answer
If the shapes are really simple (eg circles, triangles, etc), you can just generate the vertices using simple functions without going through any graphics or modeling program.
> 0 votes

---
Tags: 2d, opengl-es, art
---


# Question
Title: How to create art assets for a 3d avatar editor
I am currently prototyping an idea for an iPhone game. I'd like to create an avatar editor inside the game so that the player can create a 3d avatar face and modify certain features (using slider controls), such as nose shape, eye color, mouth size, etc. This has been done in several games, but what I'm looking to do would be fairly cartoon-ish/caricature-ish, similar to the Mii editor on the Nintendo Wii (http://www.myavatareditor.com/). I'd also like the final result to have the ability to use some canned animations, such as simple speech animations, smiling, frowning, etc.

I am not an artist, so I would be unable to create these assets, but what kind of effort is required for an artist to create the 3d models necessary for this type of game? Also what mechanism would be required to tweak the face's characteristics? Would you use bones or morph targets? How would the final result be animated? Would facial animation use bones or morph targets?

I've seen several tools that do this sort of thing too, such as FacialStudio. Are there any facial generation tools out there you'd recommend for generating some base content for this game, or should I just hire an artist to do this type of work.

Thanks!

# Answer
You're referring to two different kinds of avatar editors.

Wii's avatar editor is mostly textures with glyph bombing - moving, scaling and rotating different facial features like nose, eyes, mouth etc. The only other features there are how tall and/or (iirc) fat your character is, and these are trivial scaling operations.

More complex 3d avatar editors, like in mass effect or sims, are probably(tm) based on morph targets. The artist creates a "generic" face mesh, and lots of variants of it for each morph dimension set (like small nose, big nose, etc), and by combining all these morph dimensions, you get your final face.

At least some of the commercial solutions are based on huge databases of actual 3d-scanned faces which they have analyzed to generate a morph database, resulting in interesting dimensions like male/female or caucasian/asian, etc.
> 4 votes

---
Tags: iphone, 3d-meshes, art
---


# Question
Title: How do I draw video frames onto the screen permanently using XNA?
I have an app that plays back a video and draws the video onto the screen at a moving position. When I run the app, the video moves around the screen as it plays. Here is my `Draw` method...

```
    protected override void Draw(GameTime gameTime)
    {
        Texture2D videoTexture = null;

        if (player.State != MediaState.Stopped)
            videoTexture = player.GetTexture();

        if (videoTexture != null)
        {
            spriteBatch.Begin();
            spriteBatch.Draw(
                    videoTexture,
                    new Rectangle(x++, 0, 400, 300),  /* Where X is a class member */
                    Color.White);
            spriteBatch.End();
        }

        base.Draw(gameTime);
    }

```

The video moves horizontally acros the screen. This is not exactly as I expected since I have no lines of code that clear the screen. My question is why does it not leave a trail behind?

Also, how would I make it leave a trail behind?

# Answer
Drawing in the screen is much more than just drawing in it. A system called "double buffering" is commonly used. In double buffering, you have two canvases: a front and a back one.

Whenever you're drawing, you draw onto the back canvas, and when you're done and ready to show it into the screen, you flip the back and front canvases. If canvases weren't cleared automatically before you started drawing on them, you'd end with even frame trails on one canvas and odd frame trails on the other. Sometimes the back canvas is cleared by the video card when you flip it, sometimes it's not. Sometimes it's actually filled with garbage so you can know you didn't clear it.

However, that is not the only way to implement a graphics pipeline. There are many more, such as triple buffering, and many more esoteric ones. So you should never assume anything about data you don't explicitly save from one frame to another.

Instead, if you want to have trails as you explained, you should capture your output, store it, and when you start the next frame, draw it at the very back.
> 1 votes

# Answer
Just a bit of a guess here (after answering this question): It's possible that the video renderer is clearing the graphics memory. Perhaps it has to emulate a quirk of the Xbox GPU hardware to remain consistent on Windows. I'm not entirely sure.

But try using:

```
GraphicsDeviceManager.PreparingDeviceSettings

```

to modify:

```
GraphicsDeviceInformation.PresentationParameters.RenderTargetUsage

```

And setting it to `RenderTargetUsage.PreserveContents`.

---

I'm pretty sure you don't need to fiddle with `BeginDraw` (as Josh mentioned). Unless you've change it yourself, it should have no effect.

However you should be aware of double-buffering (as Oscar mentions) - this will probably cause the trail your video leaves behind to flicker. The simple way to solve this is to disable double-buffering. The more complicated way is to use render targets (as Roy mentions) to store your video trail (this also solves the clearing problem).
> 4 votes

# Answer
This will probably give you the correct effect without having to override BeginDraw which as Oscar Rodriguez rightfully said, is a bad idea.

```
RenderTarget2D smearRT;

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Black);

    Texture2D videoTexture = null;

    if (player.State != MediaState.Stopped)
        videoTexture = player.GetTexture();

    if (videoTexture != null)
    {
        GraphicsDevice.SetRenderTarget(smearRT);
        spriteBatch.Begin();
        spriteBatch.Draw(
                videoTexture,
                new Rectangle(x++, 0, 400, 300),  /* Where X is a class member */
                Color.White);
        spriteBatch.End();
        GraphicsDevice.SetRenderTarget(null);
    }

    spriteBatch.Begin();
    spriteBatch.Draw(smearRT, new Rectangle(0,0, 800, 600), Color.White);
    spriteBatch.End();

    base.Draw(gameTime);
}

```
> 0 votes

---
Tags: xna, windows, video
---


title: Should I start to use DX11

text:
# Question
Title: Should I start to use DX11
> **Possible Duplicate:**
> learning Direct3D 9, 10 or 11 ?

I have just started game dev and was wondering should I use DX11 or version 10?

I know AMD/nVidia now have DX11 cards but there are not many games using them now.

So should I wait untill they are mainstearm?

# Answer
Depends what you want to use it for. If you just want to play with new features and learn stuff, go right ahead! Whatever you do will be useful in the future.

If you're aiming to sell software, and want to have a large target market, it might not be the best move right now. According to steam hardware survey, only about 5% of users have dx11-capable systems, while over 50% have dx10 now. Keep in mind though that this is survey of steam users, who more likely have gaming-capable PCs, so the total market situation is probably worse.
> 5 votes

# Answer
Use DX11. You can target DX10 and DX9 feature levels from DX11 so when you're ready, you can use the additional DX11 features.
> 4 votes

---
Tags: directx, directx11
---


title: Creating the concept of Time

text:
# Question
Title: Creating the concept of Time
So I've reached the point in my exploration of gaming where I'd like to implement the concept of time into my little demo I've been building.

What are some common methodologies for creating the concept of time passing within a game?

My thoughts so far:

My game loop tends to spend a fair amount of time sitting around waiting for user input so any time system will likely need to be run in a separate thread.

What I've currently done is create a `BackgroundWorker` passing in a method that contains a loop triggering every second. This is working fine and I can output information to the console from here, etc. Inside this loop I have a `DateTime` object that is incremented by 1 minute for every realtime second. (the game begins in the year 01/01/01)

Is this a standard way of achieving this result or are there more tried and tested methods?

I'm also curious about how to go about performing time based actions (reducing player energy, moving entities around the game board, life/death etc).

Thanks for any pointers or advice. I've searched around, however I'm not familiar enough with the terms and so my searches are yielding little result on this one.

# Answer
Most game loops I've encountered like to check an input state of some kind (not wait around for input, instead have it buffered).

I'm assuming your making some game with the Command Prompt in C#. You'll probably want to buffer input via ReadLine() in a thread safe queue. You should then implement a more normal game loop in a separate thread that checks this queue for new input every frame.

Also, you should probably keep track of time with a Stopwatch object or something that is strong performance wise. (I don't think your using DateTime.Now, but if you are it's a very bad idea)

That's how I would do it. Usually, time based actions are done via keeping track of passed time and executing a step (or the entire action itself) after certain intervals of time pass. So every certain unit of time (kept track after multiple updates) you would perhaps increment the age of the player or something of that nature. When the age is incremented, certain changes will take place (defined in the player's class perhaps).

That's just one way to do it, not necessarily the only/right way of doing it.

Edit: Once you've got your game loop, you should separate logic into separate classes (one for the player, one for a plant, etc, whatever is needed). These classes should be updated by the loop and they can keep track of their aging/changes. (they should be passed some kind of timing variable or should have a way of accessing it)

Edit2: If this is more of an architecture question (kind of like how I should structure my system so that my entities \[like plants, people, etc\] will age) than it's a bit harder to answer. I would have to say that you should take into consideration the structure you already have.

I would create a list of trackers for each game object. So a plant would have 3 trackers. These trackers would keep track of time and after a certain interval (predefined for each tracker) it would set off an event (passed in as a delegate perhaps). This delegate could make the plant grow older or do whatever. Also, the delegate could return true or maybe some custom object to define whether the tracker should continue to track time and maybe at what interval it should track time, among other things.
> 5 votes

# Answer
That is the standard way of getting the time from C#. And using a BackgroundWorker I think is better than multi threading it in this particular scenario.

Though I think the above comments are a bit confused as with most games, there is no waiting around for inputs its always updating.

It will be hard to perform time based actions when you aren't using a game loop of some type. You might want to reconsider your structure. You could always have the game loop keep running, even if there is no text submitted, and when there finally is you can react upon that text.

I would either do straight text-based game, or switch over to using a game loop, if you want those added features.
> 4 votes

# Answer
If it's text-based, why not just store the starting time in a `DateTime`? Then when you need the time, just subtract that value from `DateTime.Now`, pull the `TotalSeconds` from the resulting `TimeSpan`, then add that many minutes to the starting `DateTime`?

eg:

```
private DateTime StartTime;
const DateTime StartOfGame; // = 1/1/0001 AD

void Init()
{
  StartTime = DateTime.Now;
}

void Logic()
{
  // ...
  DateTime gameTime = StartOfGame.AddMinutes((DateTime.Now - StartTime).TotalSeconds);
  // ...
}

```
> 0 votes

# Answer
With regards to your comment to Tullo

> I'm not really trying to get the time, more pass the time in such a way that players can age, plants can grow/die/breed and other time based events can occur

Why not just use a timer? Once the timer runs out, a callback function could be triggered and you would then update player age, plant status, etc in that callback function automatically.

Once you are done with that, then make sure to restart the timer again for the next aging cycle.
> 0 votes

---
Tags: c#, multithreading, game-loop, text-based, timer
---


title: DirectX10 How to use Constant Buffers

text:
# Question
Title: DirectX10 How to use Constant Buffers
I'm trying to access some variables in my shader, but I think I'm doing this wrong. Say I have a constant buffer that looks like this:

```
cbuffer perFrame
{
    float foo;
    float bar;
};

```

I got an ID3D10EffectConstantBuffer reference to it, and I can get a specific index by calling GetMemberByIndex, but how can I figure out how many members perFrame has so that I can get each member without going out of bounds?

# Answer
> 2 votes
If you have an `ID3DX10EffectVariable` that represents `perFrame`, then you should be able to call GetType to get an `ID3DX10EffectType` for `perFrame`. Then you can call GetDesc on that type instance to get a D3DX10\_EFFECT\_TYPE\_DESC which has a `Members` field which should give you want you need.

That said, I think accessing members by index is generally fairly brittle and that giving fields semantics whenever possible to more desirable.

Note that I have never actually tried this on structures denoted *cbuffer* so there may be some additional hoops you need to jump through if things don't quite work out -- constant buffers may have some specialized rules or handling via the effect interface. But I'm reasonably sure this will at least set you on the right track given that constant buffers seem to be well-understood by the API.

EDIT: I retargetted all the links to point at the D3D10 versions and not the D3D11 versions.

---
Tags: directx10
---


# Question
Title: SFML title bar with weird characters when using UTF-8
(Previously asked at https://stackoverflow.com/questions/4922478/sfml-title-bar-with-weird-characters-when-using-utf-8)

I've just started using SFML and one of the first problems I've come across is some weird characters on the the titlebar whenever I try to use accents or any other extended char.

For instance, I've got:

```
sf::RenderWindow Ventana(sf::VideoMode(800, 600, 32), "Año nuevóóó");

```

And the titlebar renders like `AÂ+o nuevoA³A³A³`

This ONLY HAPPENS if my source code file is enconded in UTF-8. If I change the file encoding to ISO-8859-1, it shows properly. Obviously all of my files use UTF-8, as its the system-wide encoding. I'm using GCC under Ubuntu GNU/Linux.

I've tried using the different utilities in `sf::Unicode` to adapt the text, but none of them seems to work.

# Answer
IF your source code file is in UTF-8 then those non-ASCII characters can be represented by more than one byte. eg. 'ó' is represented by 'A³' (or perhaps more accurately, 'ó' is represented by values that render as 'A³'). I think you should be very careful when using UTF-8 source files since C++ string literals imply 1 byte per character but UTF-8 characters break that assumption. I'd recommend switching to a fixed-width representation like ISO-8859-1 for your source files.

The SFML RenderWindow constructor takes a "const std::string &Title" - this has no encoding specified, but it gets passed through to a WindowImpl class which decides how to pass the string to the OS. It looks like Win32 makes an attempt at handling Unicode, but I don't have the Unix/X code to hand. I suggest looking through that and seeing if it does something similar. Either way, the std::string carries no encoding information at all so it's risky to use anything but ASCII, unless SFML explicitly states what kind of text encoding to supply.
> 2 votes

---
Tags: c++, sfml
---


# Question
Title: What should a game have in order to keep humans playing it?
In many entertainment professions there suggestions, loose rules, or general frameworks one follows that appeal to humans in one way or another. For instance, many movies and books follow the monomyth.

In video games I find many types of games that attract people in different ways. Some are addicted to facebook gem matching games. Others can't get enough of FPS games.

Once in awhile, though, you find a game that seems to transcend stereotypes and appeals almost immediately to everyone that plays it. For instance, Plants Versus Zombies seems to have a very, very large demographic of players. There are other games similar in reach.

I'm curious what books, blogs, etc there are that explore these game types and styles, and tries to suss out one or more popular frameworks/styles that satisfy people, while keeping them coming back for more.

# Answer
> 18 votes
I would recommend you to read A Theory of Fun for Game Design, written by Raph Koster, an experienced game designer who started as a writer.

He basically proposes that we humans are living things that love watching and learning patterns everywhere. We basically want to get better at things, and games are a powerful learning tool. Games offer simple mechanisms that add themselves up to enable players to do really complex stuff (e.g. see how a player who loves playing fighting games learns to play those games).

What makes a player to return to a game? A fun mechanism is vital, but there is also another ingredient. Remember when you learned how to play Tic-tac-toe? it was a pretty fun game until you understood how to play it, and what strategies you used to win or tie every time. When we begin doing any activity (being playing a game, playing an instrument, painting, etc.) we start to do exactly that: learn what are the best strategies to do best what we like to do. If the activity is simple enough to know those strategies quickly, then that activity becomes boring. If the activity is too complex, we also get bored and we opt out of it.

So there are two extremes, see? assuming that we like what we are doing, if it's very simple, we will get bored quickly because our brain concludes that it took everything he needed and can predict now the next steps. If it's very complex, we will also get bored because we are unable to grasp the concepts that enables us to win the game/paint nicely/play clarinet beautifully.

So games are especialized in that: they present an activity with a carefully balanced difficulty setting, so the game is easy on us when we learn the controls, but as we gain experience playing it, the difficulty keeps rising and rising.

When we get to this fragile state of mind, we call that being "in the zone". That's an important thing to achieve when designing a game, and watch people who play if they're in the zone, whether they're playing WoW or minesweeper.

You should also read the Princess Rescuing Application slides, by Daniel Cook, which also present an insight on how games trap us.

# Answer
> 10 votes
> For instance, Plants Versus Zombies seems to have a very, very large demographic of players. There are other games similar in reach.

**Take pop culture item, draw it with cute colorful cartoon art, advertise the hell out of it, offer a free demo, and make it a super Casual game with shiny things and little "ding" sounds going off all the time.**

There, the secret is out.

# Answer
> 4 votes
I think this article perfectly answers the question :)

http://www.cracked.com/article\_18461\_5-creepy-ways-video-games-are-trying-to-get-you-addicted\_p1.html

# Answer
> 3 votes
It has to be fun for the person playing it. It really is that simple. Unfortunately, there's not a recipe to creating fun; I think you just stumble upon it and you're surprised by it. That's why you see a lot of advice telling people to create games for themselves. If it's fun for you then it's not wasted effort and someone, somewhere will also enjoy it. That's where the marketing comes in to play. How do we find the people who will enjoy the game?

Anyway, trying to make a successful game is like designing by committee, it hardly ever turns out like you wanted. Design something fun for you and then you just have to find others who enjoy it.

# Answer
> 1 votes
i don't know if this answer the question, but i found this article and i thinks it is pertinent with discussion:

http://www.gamasutra.com/view/feature/6269/playing\_games\_is\_hard\_work\_an\_.php?print=1

# Answer
> 1 votes
In my mind, it first depends on the type of game. For games that requires reflexion and simples actions (meaning not immersive games), it requires artistic genius.

For games which are "immersive"-kinded (where you control one of several character in a virtual environment), it is less complicated, but it requires to have played other genre-alike games.

You have to implement mechanisms that make the player think he is in a world, make a reward system, but keeping all this simple, quick and more importantly, **coherent**. It's not because it's virtual that you can invent any rule you think is a good one and say "it'll work, it's genius": It's great that virtuality allows to do anything you want, but players want to have fun, not test your ideas.

It can seem you have to imagine you are being god and designing a world and its rules, and it can seem inappropriate, but that's the only way a game can be fun: you have to distort reality, not change it. BUT that doesn't you should not experiment, that is strongly encouraged, but if you want to implement an idea, don't forget that:

* ideas are cheap, expensive to implement
* most importantly, your idea might have to be balanced and/or adjusted before you release the game: an idea is more abstract than a state diagram, so in the end, you will have to make it do what you feel is the most appropriate.

# Answer
> 0 votes
A gun, pointed at their loved ones, and a willingness to pull the trigger if they don't come back to play your game in X hours.

# Answer
> 0 votes
Compulsion loops is one way to do it.But do note they only work to a certain degree relative to interest and attention span of a player.

Also there is no proven formula to appeal to all except the general rule of making a fun game which can also be subjective. This is probably because to be human usually means to be very varied in taste and behavior.

Note: I do believe this answer borders to the dark side of game design. =p

---
Tags: game-design
---


title: Make OpenGL game perform better

text:
# Question
Title: Make OpenGL game perform better
I have programmed an OpenGL game which just contains one F1 car and a track. It is very simple and only uses around of 10'000 - 20'000 triangles. It should run on any PC but it won't, it needs a really good graphics-card to run at a decent framerate. Can you write some methods or links to sites which would help me make my scene/game more efective?

my game can be downloaded from here

or directly from here

# Answer
> 7 votes
What I have seen, you are using Display lists. They are already few years depricated and you should use vertex buffer objects. It maybe could help.

They work on this princip: You create buffer in graphics memory. Still in init phase you copy your data there (vertex coordinates, texture coordinates, normals etc.). And always in display function just use these data to render all geometry. It's fast and most used in these days (I hope).

# Answer
> 2 votes
Go grab gDEBugger. It's free for everyone now - you just need to register to get a free 1-year license.

With it, you can check if you're fill bound, vertex processing bound, shader bound or cpu bound - as well as check if you're doing something stupid like rendering 10000 separate objects.

---
Tags: opengl, performance
---


# Question
Title: The recommended road map to be a good graphics/game engine programmer
I am a computer science student and I am developing with C/C++ and Python and I want to begin learning graphics tools to start developing with game engines, especially the Blender Game Engine. So what is your recommendation for me to learn and to read? And recommend me a road map for it.

# Answer
**EDIT START**
Not looked into blender game engine for a while, but I'd have thought the only requirement to use BGE would be to learn how to use it, like any other program.
**EDIT END**

Firstly a Game Engine and Graphics Engine are very different. A Game Engine could be thought of as lots of little engines, graphics, sound, network, input etc... A Graphics Engine such as `Ogre`, focuses entirely on the graphics side of things.

The single most important thing is `Maths`. `Maths`, `Maths`, and `Maths`. Leaving aside the physics.

`Vectors`, `Matrices`, `Quaternions`, `Ray tracing`, `curves in space`, `Projections stuff`, `Approximation methods`, it goes on ...

The maths is platform independent and will be useful on `ALL` platforms.

Also pick a graphics API such as `OpenGL` or `DirectX`, I prefer OpenGL for platform sakes, but it doesn't really matter. `XNA` would do I guess if you'd prefer C#.

A good general book on Amazon
http://www.amazon.co.uk/Essential-Mathematics-Games-Interactive-Applications/dp/0123742978/ref=sr\_1\_3?ie=UTF8&qid=1297439659&sr=8-3
> 5 votes

# Answer
You would be best served by learning how to use openGL off their site. It will introduce you to programming for graphics. Only after you are comfortable with openGl then move to creating a game loop and object manager.
> 2 votes

# Answer
Learning to be a good programmer and learning how to use the (relatively obscure and underused) Blender Game Engine are two very different problems. Almost so different that I think you should be asking two separate questions.

That said, learning the Blender Game Engine is like learning any other API or toolchain. Check out the documentation, read and understand it, and practice using it over and over until you are comfortable with it.

That general concept applies to learning how to be a good programmer as well. Generally a programmer will learn by first acquiring some basic skill with a particular programming language and then experimenting in the default environment of that language -- this typically means building text-based, console-IO type programs and games for a while. It sounds like you are there already and want to move beyond that.

At that point the programmer tends to start experimenting with windowing libraries or 2D graphics libraries. There's a big jump between console-based IO and 2D, window-oriented, event-based programming for some. Making games in this space that introduce the programmer to the fundamentals of linear algebra, which is a critical part of understanding the 3D graphics programming that many programmers eventually end up doing. Once a programmer has built a few 2D games, it may be time to consider learning 3D math and APIs (Direct3D or OpenGL, or some higher-level API provided by some engine or whatnot).

At some point during that whole process, which is very focused on the everyday minutiae of being a programmer, you will hopefully acquire a talent for larger-scale problem solving and for considering the design and architecture of the systems you build rather than just the "how to" of building them in particular languages -- this is the thing you want to strive for, this is where you start becoming a good software developer instead of a good code monkey.

In your specific case, PyGame might be a reasonable thing for you to start looking at.
> 2 votes

# Answer
If you're a computer science student, then find out what the graphics course is at your university/collage and its prerequisites. You'll probably want to take both optional and required prerequisites for the graphics, but you also need to get all of the prerequisites for the graphics prerequisites.

For example, the University of Waterloo's graphics course is CS488. The prerequisites are (CM 339/CS 341 or SE 240) and (CS 350 or SE 350) and (CS 370 or CS 371). Each of these will have their own prerequisites that you need to fit into your schedule.

While the specific courses are different for each school, I'd assume a lot of the content is similar. The UW graphics course requires students to build several small scenes and then a ray tracer. They then make a proposal for and implement their final project. You can get ahead in your education by going through the courseware for a lot of universities online: MIT, Stanford, etc... (MIT puts a lot of effort into making their courses available online.)
> 1 votes

---
Tags: graphics-programming
---


# Question
Title: How do I get started with fog type effects in a first person game?
Hey guys, I'm currently using JME3 to learn 3d game development in java, and I have run into a situation. I would like to add fog effects to my games, but I don't even know where to start to implement this. I know how to set the camera's far frustum to limit the render distance, but that just simply makes a sharp cutoff. I'd like the fog it up a bit to make it feel more natural.

**I'm looking for an answer that points me into the correct direction. I'm not looking for specific code snippets or even JME3's engine specifics. I just want to get an idea of how this stuff works in general.**

Thanks!

# Answer
One tip for choosing the color of your fog. Assuming you are using a skybox, make the fog color be the average color of your skybox on the horizon. If you do this, then as items slowly "fog out" as they become farther away, they will blend nicely into the skybox until they fade away. If you just set your fog color to white and the skybox is not white, you'll end up with white silhouettes of objects, which looks wrong.
> 8 votes

# Answer
In general fog is very simple. It just takes depth of each fragment / pixel and according to some function sets the output color (blends between original fragment color and fog color according to fragment depht). You can use linear blending or quadratic blending or whatever you want (if you implement it yourself).

I'm not java programmer so I can't say you exact commands. But in OpenGL it's very simple and in original rendering pipeline (non-programmable) it can be just enabled by one command and disabled by other. In programmable pipeline you have to write it in your shaders, but it's only blending.
> 4 votes

---
Tags: 3d, java, camera
---


title: Materials when rendering geometry

text:
# Question
Title: Materials when rendering geometry
When specifying the material (ambient/diffuse/specular) for use in lighting calculations, what level of detail is the material specified at? Per vertex, mesh, bone?

# Answer
Generally, in a stateful graphics API, a material's settings will apply to *anything* rendered after the material state is set to the API. Whether or not the effect of that material will be per-vertex or per-pixel depends on the actual vertex and fragment shading programs that execute for the rendering of each individual primitive.

If you're using the materials built in to fixed function D3D9 pipeline, then the resulting object color is vertex-oriented, but the material's impact will be apparent for every object you render until you change the material.

Writing your own material system can allow you to embed material data into the vertex attributes, if you so choose (either directly into the vertex stream or indirectly via texture lookups) and thus have finer control over the material properties of an object without having to render that object in multiple draw batches just to swap out material data.

Materials rarely apply to bones in any significant fashion (although that might make for an interested system to write: assigning materials to bones, blending material effects using the vertex weights).
> 2 votes

---
Tags: c++, directx, rendering, lighting
---


title: How do I change a sprite's color?

text:
# Question
Title: How do I change a sprite's color?
In my rhythm game, I have a note object which can be of a different color depending on the note chart. I could use a sprite sheet with all the different color variations I use, but I would prefer to parametrize this. (Each note sprite is made of different shades of a hue. For example a red note has only red, light red and dark red.)

How can I colourise a sprite anew?

I'm working with OpenGL, but any algorithm or math explanation will do. :)

# Answer
I'd probably use a single color image (eg. your note-sprite) with alpha channel and then color the whole image with your base-color. So, something like in the following image (from wikimedia commons):

If your color was red, you would then color the note (all the black parts) with the same red. What you would need in addition, is a grayscale image with the shading of the note. Then combine the shading with the flat color by using blend-modes like *Multiply* and/or *Screen*.

Another, probably simpler approach would be to just have a grayscale image where you would multiply each color component with your selected color. So if you have a gray value of `0.5`, and a red color `RGB(1.0, 0.0, 0.0)`, that would result in `RGB(0.5, 0.0, 0.0)` for the given pixel.

**Update:** Here's an example image to illustrate what I mean with the blend-modes:

Of course you could just use the *shadow* layer if you don't need the highlights (which is basically the same as the simpler approach mentioned above).
> 8 votes

# Answer
Make a greyscale (or just white) version of the image you want to show, with a suitable alpha channel. Use the vertex color to "dye" the image.

Vertex color multiplies each channel, so white x red = red, 50% grey x red = 50% red, and so on.
> 3 votes

---
Tags: opengl, sprites, color
---


# Question
Title: What are the typical day-to-day tasks of a games writer?
I am interested in plot writing for games, and wondered first of all:

Is this available as an entry-level position, or is it accessed through other avenues (even external to games development)

And secondly, what are the daily tasks of a games writer, both at the entry level and at a higher level?

Thank you.

# Answer
> 4 votes
I work at one of the relatively few studios that retain a full-time writing team. I also work very closely with the writers in my role as a tools developer. We have around seven (I think) full-time writers, including their lead, and two writer/designers who act as lore directors and generally are the final authority on the direction of the world.

For the most part, the writing team authors new text or edits existing produced by other designers. The kind of content they generate tends towards the minor characters, dialog scenes and conversation, bits of chatter and background VO, quest description, descriptions for areas -- basically, anything that needs to be written. They also work with those designers to help ensure that all the text that is produced fits within the framework of the universe we are creating -- that nobody uses anachronisms, that characters of a particular cultural background exhibit the traits of that background, that the game is not too chock-full of pop culture references, et cetera.

Our writers also work with external partners, such as the authors of books based in our world, to ensure accuracy and adherence to what is canon. Most studios maintain a "story bible" of some sort that documents these sorts of things, and maintains guidelines for what is and is not canon (ours are not public, but Bungie has published this guide to what is considered canon in Halo, for example)

If you have a strong background in literature, writing, or related fields you may be able to break in to the industry provided you can find a company that employs a team of full-time writers. This may be difficult. I would caution you that is far more about editing and creating in-the-small than it is sitting around and getting to dictate the entire plot of a game.

# Answer
> 3 votes
1. From what I've seen, IF you're already published in other media (e.g. novels), AND you have a personal connection to a game company (e.g. you're good friends with the executive producer), AND the game company is relatively small and unknown, you have a good chance of getting hired with no prior experience in the games industry. Otherwise, it's probably pretty difficult.
2. Most game writers would spend the bulk of their time writing whatever needs to be written, whether it's NPC dialogue, backstory, etc. Whatever story you write will need to be tailored for the game, and you'd be working under the direction of the lead designer, design director, producer, or other such person.

---
Tags: game-industry
---


# Question
Title: What does the term 'photorealistic' really mean?
I was wondering about the term 'photorealistic' in regards to rendering and was wondering how this is used.

Is it used to describe a shader (or set of) that have certain quantifiable features? Or any rendering thats not meant to be abstract, like the cartoon effect seen in Borderlands? Or is it just a subjective term meaning 'really really realistic'?

# Answer
> 3 votes
I've worked on a few games that have been described as photorealistic and I'd have to say it's purely subjective, especially as what we might describe as photorealistic today won't in a few years (as hardware improves, rendering gets closed to perfection and people's expectations of games goes up).

You can apply the term to anything that is rendered, I would take it to mean that what your describing looks as real as you can make it (be that the shading, textures, lighting, etc). In an ideal world, a screenshot would look just like a photo taken on a camera.

# Answer
> 10 votes
When I've seen the term "photorealistic" used, it's shorthand for "trying to be photorealistic." That is, aiming for the rendered picture to look as real as possible, and using as much real physics with regard to lighting that the machine can handle.

Most rendering is photorealistic, or trying to be. If you make a conscious choice toward the stylized, as in Borderlands, you're no longer photorealistic.

---
Tags: graphics, rendering, shaders, terminology
---


# Question
Title: Looking for architectures to develop massive multiplayer game server
Hello all Where can I find architectures and examples of building massive multiplayer game server Does the does the concept of building it on top of libenevt is right ? or I need to think more on thread per connection ? im targeting to web players playing from flash / html5 clients . Thanks

# Answer
If you are thinking about a real time MMO and not a social MMO, it would definitely be worth taking a look at MV3D which is open source. It is mainly geared towards having a less lightweight client than flash, but I'm currently using it to make a browser based game and it's going well.

For a social MMO, I'd suggest building the server on the web framework of your choice rather than making your own server application. You can architect and scale your server similar to how large websites do it. There are plenty of online resources for doing that.

For either way, a great place to look is highscalability.com. In particular, here's some info on Playfish's architecture.
> 3 votes

---
Tags: architecture, mmo, client-server
---


# Question
Title: Good practices in screen states management?
I wonder what are the best ways to organize different screens in a game?

I am thinking of it like this:

Inheriting a base State class, and overriding update and render methods, to handle the current screen. Then, under certain events a StateManager is able to activate another Screen State, and the game screen changes as only the current State is rendered.

On the activation of a new screen, effects like fading could be added, and also the same goes for its deactivation. This way a flow of screen could be made. By saying when A ends, B starts, allowing for complex animations etc.

Toughts?

# Answer
> 10 votes
I would also consider allowing a stack of states. That way when the state on top leaves, the state under activates. this is really nice for menu states. When one menu leads to another, it simply puts the next state on top. If the user wants to go back, you simply deactivate the current state and the previous state activates. Very easy for menu navigation.

Also, I would advise implementing some way to have states on top of other states while the states below the top one still draw. This could be useful for pause states, but it's up to you in the end.

Also take a look at this sample: XNA Game State Management Sample I know it's in C#, but it's a pretty decent implementation of the concept.

# Answer
> 2 votes
How to handle this really depends on what you mean by a 'screen'. Often the presentation of the game at a certain point is tied into the input system for that stage, and this is grouped together as some sort of game state object. I tend to dislike this approach because too often these states become dumping grounds for all sorts of unrelated data and functions, filling your code with de facto globals. Having a stack of states instead of a single state can facilitate some things (eg. having a menu render over the top of the game while it's paused) but complicate others (eg. needing to have a dummy state for the same menu to render correctly when the game isn't in progress).

Therefore I prefer to keep much of this information in separate objects, whether for input, world rendering, the GUI, etc. Fading one screen into another tends to just become a function of the GUI. A menu rendered over the game becomes just another GUI window paired up with the pause functionality. And so on. Complex animations don't require a game state system to work, and in fact should really be decoupled from any overall game state - you don't want to have to implement a separate state any time you want interesting interface animations, after all. You should be able to have that during normal gameplay if you choose.

---
Tags: rendering, animation, state, screen
---


# Question
Title: Calculate the Z of a line intersection given the XY coordinates?
I'm intersecting a line in 2D and I calculate the X,Y coordinates of the intersection point. What I need is the Z of the intersection point given the X,Y,Z of the line points, and the X,Y of the intersection. From what I understand of equations it should be a one-liner but I don't know enough math to get there.

# Answer
You can use either the x or the y value of the intersection to compute the z-value (using x):

```
t = (x - X1) / (X2 - X1)
z = Z1 + (Z2 - Z1) * t

```

Where x is the x-intersection. X1, X2 and Z1, Z2 are your known x and z-values, respectively, of the segment's endpoints.
> 7 votes

---
Tags: 3d, coordinates
---


# Question
Title: Which Kinect package for PC takes care of motion tracking too?
I am aware that there are opensource drivers for interfacing Kinect with the PC. My question is - the drivers at OpenKinect seems to provide only the images and depth data (from the reading of their wiki and API). It seems that you need to provide your own imaging solution.

My question is - is there any all-in-one package, with samples/sources that not only grab images from Kinect, but also do the imaging/motion detection for you?

# Answer
> 3 votes
Yes, look at **OpenNI** with the **NITE** module. It is created by Primesense, who are the people that microsoft licensed the Kinect technology from.
It has many compiled examples with it

**OpenNI** uses the concept of modules, **NITE** is a module created by Primesense that can track hand movement, and can understand gestures.

**OpenNI**
https://github.com/OpenNI/OpenNI

Branch i'm using (I'm on a Mac though)
https://github.com/avin2/SensorKinect

---
Tags: kinect
---


title: XNA Seeing through heightmap problem

text:
# Question
Title: XNA Seeing through heightmap problem
I've recently started learning how to program in 3D with XNA and I've been trying to implement a Terrain3D class(a very simple height map). I've managed to draw a simple terrain, but I'm getting a weird bug where I can see through the terrain. This bug happens when I'm looking through a hill from the map. Here is a picture of what happens:

I was wondering if this is a common mistake for starters and if any of you ever experienced the same problem and could tell me what I'm doing wrong. If it's not such an obvious problem, here is my Draw method:

```
public override void Draw()
{
    Parent.Engine.SpriteBatch.Begin(SpriteBlendMode.None,
        SpriteSortMode.Immediate, SaveStateMode.SaveState);

    Camera3D cam = (Camera3D)Parent.Engine.Services.GetService(typeof(Camera3D));
    if (cam == null)
        throw new Exception("Camera3D couldn't be found. Drawing a 3D terrain requires a 3D camera.");

    float triangleCount = indices.Length / 3f;

    basicEffect.Begin();

    basicEffect.World = worldMatrix;
    basicEffect.View = cam.ViewMatrix;
    basicEffect.Projection = cam.ProjectionMatrix;
    basicEffect.VertexColorEnabled = true;

    Parent.Engine.GraphicsDevice.VertexDeclaration = new VertexDeclaration(
        Parent.Engine.GraphicsDevice,
        VertexPositionColor.VertexElements);

    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
    {
        pass.Begin();
        Parent.Engine.GraphicsDevice.Vertices[0].SetSource(vertexBuffer, 0,
            VertexPositionColor.SizeInBytes);
        Parent.Engine.GraphicsDevice.Indices = indexBuffer;
        Parent.Engine.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
            0, 0, vertices.Length, 0, (int)triangleCount);
        pass.End();
    }

    basicEffect.End();

    Parent.Engine.SpriteBatch.End();
}

```

*Parent is just a property holding the screen that the component belongs to. Engine is a property of that parent screen holding the engine that it belongs to.*

If I should post more code(like the initialization code), then just leave a comment and I will.

# Answer
Sprite batches tend to overwrite some render states. Try to set `device.RenderState.DepthBufferWriteEnable = true;` and `device.RenderState.DepthBufferEnable;` manually. Hope that helps.
> 4 votes

# Answer
You should end your spriteBatch before doing any 3d drawing. Always keep 2d and 3d drawing separate.

By the way, why are you even beginning & ending the spritebatch if you're not drawing any 2d?

Within a spritbatch begin/end, XNA sets various renderstates for 2d drawing. Often these aren't best for 3d drawing... especially if you're using XNA 3.1. In 3.1, SpriteBatch.Begin disables the depthbuffer... which is needed for 3d drawing and could factor into your issue.

Also, if the problem turns out to be what's known as Z-fighting (it is hard to tell from the screen shot), increase your nearclip value when setting up your camera's projection matrix.
> 5 votes

---
Tags: xna, terrain-rendering, heightmap
---


# Question
Title: Where does the game code fit into the engine?
I was wondering if somebody could tell me how the game and the game engine fit into game development. What I specifically mean is, the game engine does not actually contain a game. Do game developers build an engine, then create a new class that inherits from the engine, which becomes the game?

For example,

```
class ShooterGame : public Engine
{
};

```

I'm not sure about where the game code fits into the engine.

# Answer
> 24 votes
Don't get caught up on the concept of a "game engine". While it is true that game studios often have some sort of game engine which they create in order to speed the process of producing games, many independent developers get hung up on trying to create a game engine that they never actually make something that works.

A game engine can be whatever you want it to be. If you find enough in common between your games that you can subclass an `Engine` class like your example, that's fine. If an "engine" is really just a small library of functions which you've found to be handy in past games you've developed, that's great too. Whatever it means to you, the concept of an "engine" is just reusable code to help you make more games.

If you're trying to make a game though, don't focus on making an engine. Make a game. Once the game is done and you're ready to make your second one, start making the second one, and you'll find bits that you already made in your first game; then you can extract those bits into a library or engine, to be shared between the two games. That's how an engine should be made. It's not typically something that you decide to write before making a game, because you'll end up with tons of code which is untested and you are essentially writing things before you know you need them (therefore you might not even need them). This is like premature optimization, but worse.

So to directly answer your question, basically **a game engine is a reusable "thing"** (library, tool, framework) which a game studio uses to aid in quickly producing games, and they typically create it with specific games in mind or after having created several games, extracting out the similar bits and moulding them into an engine which they know can be used in future games. It should almost never be created without either retrospect (two or more games already created) or EXTENSIVE planning.

# Answer
> 7 votes
> basically i'm unclear on where the game code fits into the engine.

Don't worry: I've worked professionally on games where we were all a bit confused on where the game code fits into the engine. ;)

I find myself saying this a lot in game development, but there is no standard system or definition for this. Some engines (typically for quite simple games) let you create new games without writing any more code at all. Other engines are basically a skeleton of an existing game and you must alter the code in-place to add your features. Some are like your example and are collections of classes which you can subclass or aggregate into your own system. Others are more like libraries of code which you add to your own application and make use of as necessary. The only thing they have in common is that the engine is the part of the system that is suitable (or claims to be suitable!) for multiple games.

# Answer
> 3 votes
I'm sure there are circumstances where people have done as you have above, but personally I've always favoured engines as a collection of libraries, with bits you can pull in as needed. That would ultimately give you more flexibility of choice to swap different components in/out based on their suitability to a specific type of game (i.e. you could choose a 2D or 3D physics library or renderer depending on the type of game) without having to have all the other alternatives resident in memory, or you could choose between a rendered based on DX9/DX11/etc).

---
Tags: software-engineering
---


# Question
Title: Any reliable polygon normal calculation code?
Do you have any reliable 3d polygonal face normal calculation code?

Any language will do, I'll port it to make it work. Even if you find some code in a 3d game engine and post it here I'll be more than grateful.

**Edit:**

I'm using this but it fails when faces are 90 degrees upright or similar.

```
        // the normal point
        var x:Number = 0;
        var y:Number = 0;
        var z:Number = 0;

        // if is a triangle with 3 points
        if (points.length == 3) {

            // read vertices of triangle
            var Ax:Number, Bx:Number, Cx:Number;
            var Ay:Number, By:Number, Cy:Number;
            var Az:Number, Bz:Number, Cz:Number;
            Ax = points[0].x;   Bx = points[1].x;   Cx = points[2].x;
            Ay = points[0].y;   By = points[1].y;   Cy = points[2].y;
            Az = points[0].z;   Bz = points[1].z;   Cz = points[2].z;

            // calculate normal of a triangle
            x = (By - Ay) * (Cz - Az) - (Bz - Az) * (Cy - Ay);
            y = (Bz - Az) * (Cx - Ax) - (Bx - Ax) * (Cz - Az);
            z = (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax);

        // if is a polygon with 4+ points
        }else if (points.length > 3){

            // calculate normal of a polygon using all points
            var n:int = points.length;
            x = 0;
            y = 0;
            z = 0

            // ensure all points above 0
            var minx:Number = 0, miny:Number = 0, minz:Number = 0;
            for (var p:int = 0, pl:int = points.length; p < pl; p++) {
                var po:_Point3D = points[p] = points[p].clone();
                if (po.x < minx) {  minx = po.x;     }
                if (po.y < miny) {  miny = po.y;     }
                if (po.z < minz) {  minz = po.z;     }
            }
            if (minx > 0 || miny > 0 || minz > 0){
                for (p = 0; p < pl; p++) {
                    po = points[p];
                    po.x -= minx;
                    po.y -= miny;
                    po.z -= minz;
                }
            }

            var cur:int = 1, prev:int = 0, next:int = 2;
            for (var i:int = 1; i <= n; i++) {

                // using Newell method
                x += points[cur].y * (points[next].z - points[prev].z);
                y += points[cur].z * (points[next].x - points[prev].x);
                z += points[cur].x * (points[next].y - points[prev].y);
                cur = (cur+1) % n;
                next = (next+1) % n;
                prev = (prev+1) % n;
            }
        }

        // length of the normal
        var length:Number = Math.sqrt(x * x + y * y + z * z);

        // if area is 0
        if (length == 0) {
            return null;

        }else{
            // turn large values into a unit vector
            x = x / length;
            y = y / length;
            z = z / length;
        }

```

**Edit:**

I can somehow display 3d arrows for each calculated normal and go so far as to document test cases where it worked and failed. But I was looking for a simpler solution, simply by using code that someone else has created and found to be working. Is OpenGL all you have? Doesn't anyone have any triangle/polygonal normal calculation code at all?

**To Jari:**

I'm using this code to calculate normals, as built from OpenGL's pseudo code. Is there something I've done wrong? and what would happen if the points are not perfectly inplane? would it fail and return a random normal or just change the normal slightly?

```
            n = points.length;
            x = y = z = 0;
            for (i = 0; i < n; i++) {
                j = (i + 1) % n;
                x += (points[i].y - points[j].y) * (points[i].z + points[j].z);
                y += (points[i].z - points[j].z) * (points[i].x + points[j].x);
                z += (points[i].x - points[j].x) * (points[i].y + points[j].y);
            }

```

# Answer
I'm successfully using this for quads / triangles.

Loop through each face, and pass in 3 verticies. If you have a quad ABCD pass in ABD. For example for the front facing face on this cube, I would pass in, v2, v3, v0

```
// cube ///////////////////////////////////////////////////////////////////////
//    v6----- v5
//   /|      /|
//  v1------v0|
//  | |     | |
//  | |v7---|-|v4
//  |/      |/
//  v2------v3

```

This is in C++ which supports operator overloading, so if in AS3 convert to Vector3d, which I notice you're not using now, might as well. ( I could see why you aren't, sometimes when trying to make found code work i also want to rule out any variables that could make it fail )

```
//  Modified from http://www.fullonsoftware.co.uk/snippets/content/Math_-_Calculating_Face_Normals.pdf
Vec3f RibbonMesh::calcNormal( const Vec3f &p1, const Vec3f &p2, const Vec3f &p3 )
{
    Vec3f V1= (p2 - p1);
    Vec3f V2 = (p3 - p1);
    Vec3f surfaceNormal;
    surfaceNormal.x = (V1.y*V2.z) - (V1.z-V2.y);
    surfaceNormal.y = - ( (V2.z * V1.x) - (V2.x * V1.z) );
    surfaceNormal.z = (V1.x*V2.y) - (V1.y*V2.x);

    // Dont forget to normalize if needed
    return surfaceNormal;
}

```

Edit: Found source where I got this from Edit: corrected calculation of z component of surface vector
> 5 votes

# Answer
OpenGL wiki's pseudocode (as referenced by Peter Taylor, as well) is correct. What you want is the normal of the *plane* the triangle, quad or other polygon represents. All you need are two edges of any planar polygon that share a common vertex.

The number of edges does not matter. All you need is to get enough information to define the plane, and then get the normal of said plane.
> 8 votes

# Answer
A cross product ought to be perfectly reliable for any planar polygon. If you've got problems with that, it's almost certainly just a bug in your code.

As others have said, it would be useful to know why you think your normals are wrong.
> 2 votes

# Answer
I'll post my solution too, it takes the average of the normals of all triangles that a vertex belongs to.

It takes a mesh with vertices and indices and calculates the normals for all vertices.

```
for(int i = 0; i < indices.Length; i += 3)
{
   Vector3 v0 = vertices[indicies[i]].Position;
   Vector3 v1 = vertices[indicies[i+1]].Position;
   Vector3 v2 = vertices[indicies[i+2]].Position;

   Vector3 normal = Vector3.Normalize(Vector3.Cross(v2 - v0, v1 - v0)); //This is the normal of the triangle if that's all you're interested in.

   vertices[indicies[i]].Normal += normal;
   vertices[indicies[i+1]].Normal += normal;
   vertices[indicies[i+2]].Normal += normal;
}
for(int i = 0; i < vertices.Length; i++)
{
   vertices[i].Normal = Vector3.Normalize(vertices[i].Normal);
}

```
> 2 votes

# Answer
It may be mathematically equivalent - check it if you want - but the code given there is not the same as the pseudocode for Newell's method given on the OpenGL wiki. See http://www.opengl.org/wiki/Calculating\_a\_Surface\_Normal
> 1 votes

---
Tags: normal-generation
---


title: Voronoi regions of a (convex) polygon

text:
# Question
Title: Voronoi regions of a (convex) polygon
I'm looking to add circle-polygon collisions to my Separating Axis Theorem collision detection.

The metanet software tutorial (http://www.metanetsoftware.com/technique/tutorialA.html#section3) on SAT, which I discovered in the answer to a question I found when searching, talks about voronoi regions.

I'm having trouble finding material on how I would calculate these regions for an arbitrary convex polygon and also how I would determine if a point is in one + which.

The tutorial does contain source code but it's a .fla and I don't have Flash unfortunately.

# Answer
If you want to compute voronoi diagram of arbitrary (convex or non-convex) polygon, where elements are vertices and edges, you can use Fortune's sweep line algorithm, but you have to split polygon to line segments (edges). But I don't think you should use it - it's really hard to implement, especially for line segments.

In which region is your point is another problem (point location problem) - most used method is trapezoidal decomposition (I think) - it's build on space partitioning (your voronoi region) and search complexity should be O(log n).

I think you can find much easier way how to compute circle-polygon intersection test that with voronoi diagram and point location.
> 2 votes

# Answer
I didn't have to calculate voronoi regions for my SAT implementation. I implemented circle vs. polygon intersection as described here: http://www.sevenson.com.au/actionscript/sat/ and it worked fine (also have a look at the links at the bottom of the article).
> 1 votes

---
Tags: 2d, mathematics, collision-detection, physics, geometry
---


# Question
Title: What are the benefits of designing a KeyBinding relay?
The input system of Quake3 is handled using a Keybinding relay, whereby each keypress is matched against a 'binding' which is then passed to the CLI along with a time stamp of when the keypress (or release) occurred.

I just wanted to get an idea from developers what they considered to be the key benefits of designing your input system around this approach?
One thing i don't particularly like is the appending of the timestamp to the bound command. This seems like a bit of a hack to bend the CLI into handling the games input?
Also I feel that detecting the keypress only to add the command to a stream of text that gets parsed at a later date to be a slightly latent way of responding to input? (or is this unfounded?)

The only real benefit i can see is that it allows you to bind 'complex' commands to keypresses; like 'switch weapon;+fire;' for example. Or maybe for journaling purposes?

Thanks for any insights!

# Answer
* It makes it very easy to implement customizable button assignment in your game.
* It makes programming very easy because you can think in abstract terms: You only have to decide what shall happen if the player input is "forward" for example, whether this "forward" comes from pressing the *up key*, *w*, an *analog stick* or even a *combination of keys*.
* A keybinding relay is an abstract concept and your implementation can differ from the one of Quake3. For example I wouldn't implement a timestamp if I didn't need a replay function. The overhead you're worried about is negligible if you query the whole controller state at once.
> 8 votes

---
Tags: architecture, input
---