# Question
Title: How to get the physics just right in a physics driven game
I'm working on a physics driven game using a java port of Bullet (JBullet).

In our game we have a ball that can have collisions with the other objects, including the objects that define the boundaries of the playing area.

Since we consider collisions between the ball and other objects as a very important aspect of the gameplay we wish to handle those collisions in our own code. This allows us to get non-realistic but very controllable behavior for the ball.

The other gameobjects also collide with each other, but JBullet handles those collisions well and we have no issues there.

The problem is that we have great difficulty triggering the custom behavior in the correct way. In our first set-up called our custom collision handling code every time JBullet reported a collision for the ball. This caused undesired behavior as a single hit could trigger multiple reported collisions. Which caused the ball to be sort of glued to the wall.

Our "fix" for this was to have the ball keep a timer and to ignore subsequent collisions occurring within let say 0.1 second of another. However, this caused ball to bounce through walls in some cases, probably because the first reported collision isn't the one we expect, and the ball-wall collision occurring shortly after is sadly ignored.

So that brings me to my question. How does one sort this out without resorting to all sort of "fixes" that only make the problem more complicated and less predictable?

Would for instance placing the ball at the last known position before the collision and handling the collision from there work? But what if another object has moved to that position in the mean time.

Or maybe calculate future collisions with the ball for non-moving objects and enforcing them if they are missed by the physics?

Any feedback / thoughts / revelations would be greatly appreciated!

# Answer
About objects sticking to one another, that is a classic flaw in impulse physics simulation engines, it happens when two objects haven't cleared each other completely after a collision, the collision formula will then shift them back to move towards one another, and they will stick to this pattern until something disturbs it. The simplest way to deal with this problem is to check if the two objects are actually moving towards one another, if not, don't respond to the collision.

As for using custom handling on top of a prebuilt library, beware about it, when you open the black box you will have to understand what goes on inside it in order to be sure that you don't break anything. In some cases rolling your own physics could be a better alternative, you would certainly gain a lot of useful knowledge for tinkering with physics this way.
> 2 votes

---
Tags: physics, game-mechanics, game-design
---


# Question
Title: XNA 4.0: Animating a moving 2D sprite (not via user input)
I see a lot of tutorials explaining how to do 2D Sprite Animation with sprite sheets, based on the user's input (i.e. Move Left, Move Right ) etc.. etc..

I have already incorporated an AnimationManager in my game to handle these types of animations.

What I would like to do however is *to play* animations that have a set start and end position with a given speed. I'm trying to think of how I'd like to do it and perhaps leverage some of the already written Animation code I have.

Things that I feel stumped about:

1. Should I use a timer? How will I increment the Sprite's position based on the speed otherwise? It makes logical sense to perhaps put it in the Update() however then I would need to keep track of whether the sprite is animating and the desired final Position?
2. Clearly the speed of the animation (FPS) should depend on the distance I'd like to travel so that the animation runs throughout the length of any distance?
3. Who should handle the moving of the position and animation if it's dependant on a distance? My animationManager or the sprite himself?

I couldn't seem to find any demo/example code online, so any feedback or links I'd greatly appreciate!

I'll post my AnimationManager so far to give a fill of what I'm working with:

```
    public class AnimationManager
{
    #region Member Variables
    public delegate void AnimationComplete();
    public event AnimationComplete AnimationFinished;

    private Dictionary<String, Animation> _animations = null;
    private Animation _currentAnimation;
    private int _frameIndex;
    private float _elapsedTime;
    private AnimatedSprite _sprite;
    #endregion

    #region Initializers
    public AnimationManager(AnimatedSprite sprite)
    {
        _animations = new Dictionary<string, Animation>();
        _frameIndex = 0;
        _elapsedTime = 0f;
        _currentAnimation = null;
        _sprite = sprite;
    }
    #endregion

    #region Public Methods

    public void Update(GameTime gameTime)
    {
        if (_currentAnimation == null)
            return;

        _elapsedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (_elapsedTime > _currentAnimation.TimePerFrame)
        {
            _frameIndex++;

            if (_frameIndex > _currentAnimation.NumberOfFrames - 1 && !_currentAnimation.IsLooping)
            {
                _frameIndex--;
                OnAnimationComplete();
            }

            _frameIndex = _frameIndex % _currentAnimation.NumberOfFrames;
            _elapsedTime -= _currentAnimation.TimePerFrame;
        }
    }

    public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(_currentAnimation.Texture, _sprite.Position, _currentAnimation.GetFrame(_frameIndex).toRectangle(), Color.White, _sprite.Rotation, _currentAnimation.Origin, _sprite.Scale, SpriteEffects.None, _sprite.Layer);
    }

    public void PlayAnimation(String key)
    {
        Animation anim = _animations[key];
        PlayAnimation(anim);
    }

    public void AddAnimation(Animation anim, String key)
    {
        _animations[key] = anim;
    }

    public Animation GetAnimation(String key)
    {
        return _animations[key];
    }

    #endregion

    #region Private/Protected Methods

    protected virtual void PlayAnimation(Animation anim)
    {
        if (_currentAnimation == anim)
            return;

        _currentAnimation = anim;
        _frameIndex = 0;
    }

    // Invoke the Changed event; called whenever list changes
    protected virtual void OnAnimationComplete()
    {
        if (AnimationFinished != null)
            AnimationFinished();
    }

    #endregion
}
    public class Animation
{
        #region Fields
    protected String _name;
    protected List<Frame> _frames;
    protected Texture2D _spriteSheet;
    protected float _framesPerSec;
    protected bool _looping;
    protected int _width;
    protected int _height;
    protected Vector2 _origin;
    protected Animation _nextAnimation = null;
    #endregion

    #region Properties

    public Animation NextAnimation
    {
        get { return _nextAnimation; }
        set { _nextAnimation = value; }
    }

    public float TimePerFrame
    {
        get { return 1.0f / (float)_framesPerSec; }
    }

    public Vector2 Origin
    {
        set { _origin = value; }
        get { return _origin; }
    }

    public Texture2D Texture
    {
        get { return _spriteSheet; }
    }

    public int Width
    {
        get { return _width; }
    }

    public int Height
    {
        get { return _height; }
    }

    public String Name
    {
        get { return _name; }
    }

    public float Speed
    {
        get { return _framesPerSec; }
        set { _framesPerSec = value; }
    }

    public bool IsLooping
    {
        get { return _looping; }
    }

    public int NumberOfFrames
    {
        get { return _frames.Count ; }
    }
    #endregion

    #region Initialization

    public Animation(String name,  Texture2D spriteSheet, bool looping, float speed, int width, int height)
    {
        _name = name;
        _frames = new List<Frame>();
        _spriteSheet = spriteSheet;
        _framesPerSec = speed;
        _looping = looping;
        _width = width;
        _height = height;
        _origin = Vector2.Zero;
    }

    #endregion

    public void AddFrame(Vector2 pos)
    {
        _frames.Add(new Frame(pos, _width, _height));
    }

    public Animation.Frame GetFrame(int frameIndex)
    {
        return _frames[frameIndex];
    }

}

```

# Answer
> 1 votes
`(Total Distance / Distance per Second)` should tell you how many seconds it will take to get from where you are, to where you want to be. Call it `totalSeconds`

`totalSeconds / Animation FPS` tells us how long each frame should be displayed for. Call it `frameTime`

Now you just need to have a `TimeSpan` that accumulates the delta times:

```
timeSinceLastFrame = timeSinceLastFrame.AddSeceonds(gameTime.ElapsedGameTime.TotalSeconds);

```

(or something like that). If the `timeSinceLastFrame` is greater than the 'frameTime', show the next frame and subtract the frame time from the `timeSinceLastFrame`:

```
timeSinceLastFrame = timeSinceLastStageChange.Subtract(new TimeSpan(0, 0, 0, 0, frameTime));

```

Subtracting the frame time in this way makes sure that we don't lose small pieces of our timing mechanism. And that's it. This should move the frame forward through a fixed number of frames over a set world distance.

# Answer
> 3 votes
1. Look into interpolation. It is a fancy word for moving something from A to B over a specified time. Take a look at this post. He explains it in detail, gives the code, and tell you how to use it. I use this anytime I need to move something from A to B.
2. If you want to only have the animation loop 1 time through the movement, then yes adjust the FPS depending on your distance of travel. Keep in mind that the animation will play slower for longer distances. If you are having the sprite walk then it might look funny. Most of the time the animation should just be played at a constant FPS. Once you reach your target position you can stop it
3. Regarding who should make him move, it kind of depends on your architecture. I like to design it so the sprite keeps track of the input and moves himself (assuming it is a player controlled character. In your case I would skip the input check and just run the interpolator.

So how can *you* do it? It is hard to recommend something when I don't have the whole picture. Going by what I do know though what if you tried this.

```
class AnimatedSprite
{
    Vector2 position;

    public AnimatedSprite(Vector2 posA, Vector2 posB, float timeToTake)
    {
        this.position = posA;
        Interpolator.Create(posA.X, posB.X, timeToTake, i=>this.position.X=i.value,null);
    }

    //somewhere (whether here or in your main loop..doesnt matter) call update on the interpolator class
    void Update(GameTime gameTime)
    {
        Interpolator.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
    }
}

```

Now you just add the sprite to the AnimationManager, and do what ever it needs.

It might be important to point out that the interpolator class can only increment one float. So if you wanted to animated over X and Y you would create *two* interpolators - one for each one. You still only need to call `Update()` one time though. If you wanted you can even extend the code to interpolate over multiple points. Allowing you to move the sprite along a curve.

---

It looks like he updated the code. As far as I can tell the latest version is here

---
Tags: xna, 2d, animation, xna-4.0, sprites
---


# Question
Title: What are the best ways to serialize and unserialize network messages for C/C++ multiplayer game?
We are using JSON right now and want to move to a binary format for some types of messages between client and server.

Should I just read structs into the socket? Use proticol buffers/thrift?

How should I represent arrays of data?

What should the interface look like for packing/unpacking data?

# Answer
Assuming...

1. you are talking about converting to a buffer of bytes
2. You are using UDP and performance is a concern

Try to avoid wasting space in your packet for defining structure. I.E. send, at minimum, a byte to denote the type of packet, then just assume each packet received follows the predefined structure for that type of packet

> Should I just read structs into the socket? Use proticol buffers/thrift?

* Yes, read the whole struct IF you NEED the whole struct
* No, make the packet structure yourself, This will surely be smaller than serialization using these methods; you should know exactly what data the packet should include

> How should I represent arrays of data?

* As arrays of data. When receiving continue reading the buffer until end of data to avoid sending a Count of the array's elements

> What should the interface look like for packing/unpacking data?

* You could easily setup a bunch of methods to convert basic types to bytes, from there build on these methods to convert custom types as well. The specifics on *how* to do this could be found almost anywhere I'm sure (I use C# personally)

One last thing, packet size *is* a concern, especially for a snapshot: size = packetSize x entities x connectedPlayers; So you might have 60 x 10 x 16 = 9,600 bytes per packet Then sending this 20 times a second: = 192,000 bps = 187 KBps. This is obviously a high bandwith upload speed. Thus the need to minimize each of the factors contributing to packet size where possible.

This article has helped me immensely: Valve Multiplayer Networking
> 12 votes

# Answer
This problem has been solved by Google and Facebook:

1. Google's Protocol Buffers — Google is a big user of C++:

> Protocol Buffers are a way of encoding structured data in an efficient yet extensible format. Google uses Protocol Buffers for almost all of its internal RPC protocols and file formats.
2. Apache Thrift (formerly by Facebook):

> Thrift is a software framework for scalable cross-language services development. It combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml.
> 1 votes

---
Tags: c++, networking, multiplayer, c
---


# Question
Title: Rate-limiting players actions in a multiplayer game
I'm thinking about building a multiplayer game with combat between players and monsters. Actors need to have a maximum actions per minute, otherwise users could cheat by holding down the attack key. Plus, I'd like to vary the maximum APM depending on the player class and monster.

How should I handle rate limiting combat in my game?

Assuming every actor has a timestamp of when their last action occurred, should I queue up actions to execute or should I drop them if they're received too early? Can you think of any reading material or examples I could research?

# Answer
That time stamp should be from the server's receipt, never trust player data.

The two most enjoyable experiences, in my opinion, come from one of these two options:

1: For a more twitchy, timing based game drop everything that's too early, these are most assuredly the player spamming his input keys. If you have classes of actions with different APM limits you can tune some actions to be more responsive with a fast turn around while other actions have longer recycle times and this gives you flexibility to balance game play and make it feel fun.

2: For a more MMO feel buffer ahead just one command that was sent too early, game play feels more strategic and forgiving of player timing. I would game play test buffering strategies to see whether holding just the first command or the latest command to play when the timer is up, the only way to tell which feels better and is more fun for the players.

I don't have any references to cite because every game is tuned specifically to fit its own play design. So whatever you do, try to make the system flexible and data driven so you can tune the feel with as little extra work as possible.

I'd like to be more helpful but it really does come down to experimenting to see what feels best to your players.
> 4 votes

---
Tags: multiplayer, mmo, combat
---


# Question
Title: Game (X-Plane) boot/startup time / performance
I use X-Plane for my question but it also concerns probably every other flight-simulator or simulation game in general. When developing a plugin what bothers me most is the startup-time of the application to test my plugin functionality so I was wondering how I can improve the startup speed of the simulator.

First I removed all additional scenery and reduced the loaded files to a minimum which gave me a startup time of 34 seconds which is quite fast already. To improve the time even further I thought it would make sense to run the whole application from memory and I installed ubuntu 64-bit and created a 2GB tempfs filesystem in memory (ram-disk).

When starting x-plane from this memory file system it still takes 30 seconds. Can anyone explain what the application does during startup which needs so much processing time?

I assume that the graphic bitmaps for the object and the environment are compressed on disk and therefore they have to be decompressed in memory first before they can be used in opengl. This would explain the time spent on startup.

If it is true that the bitmaps need to be decompressed first would it be possible to improve the time by using multiple cores? If the application is multithreaded and there are four cores would the time be divided by four or does this processing happen on the GPU?

Any explanation which helps me to better understand the startup-process of a computer game is really appreciated because I'm interested in improving the overall performance of the system and therefore I need a better understanding of the bottlenecks (RAM, CPU, GPU, Disks (SSD/Raid), OS, libraries, ...).

# Answer
> 1 votes
What you need to do is use a profiler to analyze where the time is going. All games are different and there's no generic answer to what they might do during startup other than loading data off disc and preparing it for use.

However some common ways to optimize startup time are:

1. Organize the data on disc into a single big file, that contains everything you want to load in the order you load it (or as close as possible if the data that's loaded varies). This minimizes the number of seeks required which can add up quickly when you're loading lots of small files. This is less important when you're repeatedly loading the same game though as the O/S disc cache should optimize this for you.
2. Move CPU work from game startup to a data preprocessing tool. That means what you're loading off disc will then require minimal CPU work to get it ready for use. Concentrate on the most time consuming data to load first (based on the profiler results).

---
Tags: opengl, performance, simulations, compression, hardware-acceleration
---


# Question
Title: Learning GLSL: What's a good intermediate project to work on?
I know the basics of OpenGL and I'm starting to love computer graphics more and more. I have a computer science background and have been programming for 5 years. I've been reading the orange book and kind of want to figure out a project that can push me to the next level. I don't want it to be over overwhelmingly hard, I just want a project that can help me progress.

As, of right now I've played around with basic programs in the book. Changing parameters seeing how data moves from one shader to the next.

Any Ideas of what might be a good intermediate project to tackle?

# Answer
Instead of starting a bigger project to improve your skills, just make a few demos. GLSL programs tend to be pretty small, with bigger projects you spend too much time writing frameworks/opengl than actual GLSL programs. Simply start with a opengl library that lets you write GLSL (can be some old code, ogre, ardor3d, etc) such that you won't waste too much time on other things.

I would start with off porting basic rendering from the fixed function pipeline to GLSL to get a feel for it (implement per pixel lightning). Then start with some basic bump mapping, improve it with Parallax mapping, etc. Make sure you really understand everything before going on to the next project.

Then just look around the net, if you see something you like, try to implement it yourself. GPU gems (nvidia) is a great source of inspiration.

Once you know a little more, try to implement effects like deferred shading, sky scattering and depth of field. After that you'll definitely have a good feeling about what is possible with GLSL.
> 2 votes

---
Tags: glsl
---


# Question
Title: XNA 4.0: Trouble Aligning an Animating Sprite (Texture Origin)
I'll try to explain this as best as I can.

I'm trying to build a game where there exists a "Surfer" who is surfing down a rail. I have a sprite sheet for the surfer however I have been running into animating the surfer for the following reasons:

1. The source rectangles for each animation are sometimes different
2. The **feet** of the surfer are at different locations within each texture animation.

What do I mean by #2? For instance, I have an animation for the surfer to jump rails. My spritesheet is built so that my surfer's feet might be positioned on the left side of the texture at the start of the animation and after the jump (iterating through the textures) his feet are now at the right hand side of the texture.

This is causing me problems because in order to align the feet to the rail for each animation I tried to offset the origin of the texture so that it points at his feet.

(The origin is given in the SpriteBatch.Draw call)

However this isn't working :(

Any recommendations on how to properly set this up?

PS: I Hope I explained it well, if not I can edit it and retry.

# Answer
> 3 votes
I would just fix the spritesheet. Seems like it would be a lot easier to adjust the position of each frame in the sheet rather than adjust the rectangle for each frame.

I would also try to keep him centered in each frame. You should move the sprite around by position the image, not by shifting where the image is in the frame. that just adds confusion, and complexity that you don't really need.

It doesn't really matter if the image in each rectangle is a different size. (What I mean is a guy standing vs crouching.) You should still aim to keep your source rectangle the same size. Just make the extra space transparent.

# Answer
> 1 votes
Often, sprites like this surfer come with some kind of meta-data that describes the varying frame sizes, and hopefully the feet positions.

If you can't find this meta-data, I would recommend either making it, or following Joe's suggestion to make the frames all a standard width and height, and try to place the surfer's feet in the same (x,y) offset from the upper left corner of the frame.

---
Tags: xna, 2d, animation, xna-4.0, sprites
---


# Question
Title: Good practices to hold terrain data in a 2D networked game
I am working on a client-server architecture game, its a 2D top view adventure.

My main focus for the map system right now is to have editable terrain, that will actually change in realtime to other players!

So, i've divided the map into equally sized chunks, that coupled together form the whole map. As the client camera moves, the server will be sending updates for the neighbour chunk, allowing the client to show the map up to date, without having it locally, and seamless.

And this is what brings the problem, if a whole chunk is going through the network, the data for its terrain must be clever built.

Making this edition and storing like traditional Tilemaps would seem a little overhead for a online game.. I tought of representing terrain as shapes of a certain texture, with certain parameters. All textures would be in client, with a id associated to each one. The server would send something like "AddShape \[dirttextureid\] \[point1\] \[point2\]" and the client would convert that into a dirt road between point1 and point2, but that seems to take a lot of freedom of the map creation process as there would be no freehand painting at all, causing the person to overdraw with shapes.

The rendering itself should be painless anyway, as i intend to draw all terrain in a few textures, only rebuilding those textures when something changed in the terrain, allowing the onscreen terrain to render with 3-4 sprites, leaving the rest of the cpu to draw other objects.

So, any toughts on how i can allow map editing and storing in a clever way, giving a good freedom/performance tradeoff?

# Answer
Obviously, the server will know when a client needs to request the current condition of a terrain chunk. If the server is also told when a client unloads a chunk, it can use the knowledge of loads/unloads to maintain a list of which chunks each connected client is currently tracking.

When a terrain tile is changed on the server, it can inform all clients that are tracking the accompanied chunk that the tile has changed. From your description it sounds like the only change is what tile texture to use so the message could be as simple as "`TerrainUpdate [Chunk ID] [Tile position] [New Texture ID]`" (or whatever actually fits your architecture). If you can change more than the texture, similar messages can be sent for various changes. If a series of tiles are changed, like in your example, just send one message for each tile.

Unless you have a whole lot of network traffic and/or chunks are enormous, I don't think you need to worry too much about performance with this method.
> 1 votes

---
Tags: 2d, data-structure, terrain
---


# Question
Title: When rendering on two different computers, the texture is glitchy
I am using Ogre3D, and have been using it for a while. Also lately, I have been using the Opengl Rendering system that is included in Ogre, only because Directx will not compile correctly(Will post errors on request through comment).

But as of now the main problem is when i render my model(it is a plane with simple, unblended pixelated texture), it looks like this on my Laptop(Left Image), but when I render on the desktop(Right Image), it looks the way its supposed to be.

Im pretty sure this problem might not be relevant to this site, but im not sure on where else to post this(if it needs to be moved then so be it), but i felt it would fit here just a bit, since its a game-dev type question.

Anyways, My compiler is MinGW that uses the IDE Code::Blocks. also the operating system that im using on both computers are windows Vista 32 bit.

Now if anyone would know why this would happen then please do tell(but my guess is that maybe the graphics card is not compatible)

Here are the images:

Left:Laptop

Right:Desktop

there both about the same image, and if you notice on the desktop screenshot: it looks more clearer and you can see the "mountains" better, where on the laptop picture, you cant see any pattern at all...Also, you can notice an odd stopping of light(or maybe called something else), but that has me confused also.

# Answer
Could it be about the texture filters? Anisotropic Filtering (wikipedia)

Many laptop chipsets don't support features such as good filtering, some of them don't even have vertex shaders in hardware. I know DirectX emulate some things in software when the hardware feature is not available, but I didn't work with OpenGL so I wouldn't know. With direct3d 9 you can check the caps of the device, I still don't know in DX10 how it works. Anisotropic Texture Filtering (Direct3D 9)
> 1 votes

---
Tags: c++, opengl, textures, windows, ogre
---


# Question
Title: Should I use different object types for different kind of 3D meshes?
well...

I'm building the animation system of my game engine (the skeletal and skinned animation stuff), and I came to a point where I added so much functionality in the frame and node structures that it seems to be excessive for some applications, and it ends up adding too much complexity when working with simpler objects. Objects like boxes or simple meshes that are meant to be static objects would end up with complex properties such as the ability of having a node hierarchy and transformation frames, animation type checks, and also require a lot of unnecessary creation parameters that make really hard to work with when coding some functions that use them.

I was thinking of making ie. SimpleMesh and HierarchyMesh objects, which will also require that the renderer can deal with different types of objects in the same scene. I was also thinking about making a MeshNode class and then make a Mesh object that contains them, but then I have some conflict on where to store some data, as some meshes will have per-node shaders and other will have a single shader for the whole mesh, then storing the shader references in the node will be a redundance for complex meshes that share the same shader in every node.

Other option I was thinking was making some helper functions to deal with the simpler cases, which would set some default parameters and would ask only the most basic ones, for example

```
CreateSingleFrameMesh( pTextureName, pBuffers, nBuffers, Material, &pCreatedMesh );

```

but I'm not sure if this would be too time consuming and require too much memory for storing something that will be default values in most of the scene objects (I believe the scene won't be built from skinned hierarchy meshes but mostly static and even in some cases the animation is purely a shader thing which renders useless most of the animation property in the c++ side )

Also files are required to store the minimum data required to rebuild the mesh, so in smaller meshes or meshes without animation I would end up storing a lot of data that I don't really need, even if I'm indexing node and frame data when saving and then store the hierarchy with the indices to the actual data.

I don't know if my speculations are ok, as I don't have much experience with 3d animations yet. I want to make a well decision as any option I choose would require a lot of work to get it to render and I don't want to find out in the end that I have to rewrite everything again, as a lot of other objects will be working with these data.

Sorry if it's a too subjective matter, but I need some insight. I'm full of questions about this..

Thanks in advance.

EDIT: I'm gonna add some code about it

Yes probably I'm mixing up things, but it's complicated because there are a lot of data:

```
struct INDEXEDGEOMETRY_DATA
{
    INT32           nIndexBufferID;
    INT32           nVertexBufferID;
    UINT32          nIndexOffset;
    UINT32          nVertexOffset;
    UINT32          nIndexCount;
    UINT32          nVertexCount;
};
struct TEXTURE_DATA
{
    UINT32          nTextureID;
    INT32           nImageID;       // reference the hardware image for this node (a video device texture)
    IMAGE_USAGE     nImageUsage;    // the way each image is applied in the node (color, bumpmap, etc)
    Vector2         vImageOffset;   // the offset for each image applied in the node (in pixels? o.O normalized coords?)
    SPRITE_DATA*    pSpriteData;    // Set to NULL or point to sprite-like animation data.
};
// This structure holds data about properties of an animation frame
// Note that all these data may vary between frames,
struct FRAME3D_DATA
{
    UINT32                  nFrameID;       // Frame identifier
    float                   fTime;          // this frame starts at the given fTime (or lasts fTime, i'll see that later)
    Vector3                 vScale;         // this is interpolated and then applied for each node before the global transform
    Quaternion              qOrientation;   // this is interpolated and then applied for each node before the global transform
    Vector3                 vPosition;      // this is interpolated and then applied for each node before the global transform
    MATERIAL                Material;       // the base color of the object (set to 100% white to just use the texture color)
    float                   fReflectionAlpha;// The alpha value of the reflection (a transition of this value can be used to achieve some effects)
    bool                    bHidden;        // Set this variable to true to skip rendering this frame
    bool                    bAlpha;         // Set this variable to true in order to enable use of the fAlpha variable (otherwise it's gonna be discarded)
    float                   fAlpha;         // Set this variable in order to change the global alpha value for this frame
    LIGHT_TYPE              nApplyLights;   // Set the light types that will be processed for this node. If it's set to GLIGHTTYPE_NONE, the node will rendered with raw vertex and/or texture colors
    UINT8                   nBufferCount;   // The amount of buffers used by this node
    GEOMETRYBUFFER_DATA**   ppBufferData;   // these are the geometry buffers
    UINT32                  nLightCount;    // Store here the amount of lights
    LIGHT_DATA**            ppLightData;    // Store here the pointers to the light data
    UINT32                  nTextureCount;
    TEXTURE_DATA*           pTextureData[GMAX_TEXREF];
};

```

But then any change to the frame DATA will require that the other values get duplicated. So now I was thinking about making smaller structures with the fTime variable each so I can have attribute keyframes, light keyframes and buffer keyframes, then make the node structure look like this:

```
struct NODE3D_DATA { UINT   nNodeID;
    UINT                    nTransformFrames;
    FRAMETRANSFORM_DATA**   ppTransformFrames;
    UINT                    nAttributeFrames;
    FRAMEATTRIBUTE_DATA**   ppAttributeFrames;
    UINT                    nLightFrames;
    FRAMELIGHT_DATA**       ppLightFrames;
    UINT32                  nGeometryFrames;    // Store here the amount of buffer keyframes
    GEOMETRYFRAME_DATA**    ppGeometryFrames;   // Store here the pointers to the buffer data?
}

```

then probably:

```
struct GEOMETRYFRAME_DATA { float fTime; // or uint or whatever
    UINT nBufferCount; //
    INDEXEDGEOMETRY_DATA** ppGeometryBuffers;
}

```

Other ways I have tried or thought about seem to be even more redundant, and in the cases that they don't, the performance loss is untolerable for my needs. Ah and I forgot to mention that nodes can have hierarchy, but this is not a problem if the frame data is reduced. The structure instances don't get duplicated *unless any value changes*. When constructing a node object it's done referencing a pool of structure instances to prevent allocation for 2 equal frames. Also the lights are something that I'm not sure on how to handle as I need them to be attached to the node in most cases, even if I allow setting global lights to the scene.

@Nicol: Yes that's what I'm trying to figure out. You can see the code doesn't rely on any hardware in particular or contains any game attributes, it's just keyframed animation data and some IDs for them and to reference API objects. I use objects such as CFrame to hold pointers to frame data and to store runtime values. The thing is I don't want to create layers unless it's really worth it, to prevent excessive distinction for small values, such as a making a frame object to store only the Diffuse color variation or making it store any value that can change but making it so random that I woulnd't know how to relate the data to the other frames, or need a complex system for it. That's why at this level I prefer to have well-defined data so I can store and work with fast during runtime.

It's this complicated because it must support a lot of rendering and animation techniques, must support being accessed by game entities and other objects, and must allow (somewhat)easy optimization for them if needed.

Anything that helps me make a decision is a good answer for my question, thanks for the reply.

# Answer
> 4 votes
I'd say that your main problem is that you're giving meshes non-mesh properties, thus leading to a fat interface.

A mesh is a set of per-vertex data and the information about what those vertex attributes means. That's all it should be. It may have some information, like where the "center" of it is and a bounding box perhaps, but that's about it. A mesh should have no understand of animations. It should not have a world-space position. Meshes should not have shaders. And so forth.

All of that information should live elsewhere.

As to the specific division of information, that depends on your needs. I would design it based on layered functionality. Figure out what things need to talk to each other, then build objects that facilitate this communication. For example, a mesh holds vertex data. But that alone isn't enough to render it; you need a material, which contains the shader and associated parameters necessary for rendering. So a renderable object would contain a reference to a material and a mesh.

---
Tags: c++, animation, graphics-programming, 3d-meshes
---


title: How to decrease velocity constantly?

text:
# Question
Title: How to decrease velocity constantly?
I am developing a golf game using the GameSalad framework for iPhone. I have one attribute named speed of type integer with value 5000. I also have one boolean attribute named speedControl which is initially false.

When the ball is pressed and its sppedControl is true, I accelerate it with game.speed i.e. 5000.

Now I want to decrease the speed of the ball every 0.5 seconds, so i added a timer behavior and set it to every 0.5 seconds. Every tick of the timer, I set the CHANGE ATTRIBUTE game.speed to game.speed-300. but it's not working.

Sorry, I have no reputation, therefore I can't send you screenshots.

Please help me. I am very new to GameSalad and this is my first project.

# Answer
> 1 votes
Why do you want to decrease the velocity every 0.5 seconds, rather than modelling the forces acting on the ball accurately (in a perfect world)? This is not too complicated and will be far more realistic.

Rather than setting a speed, consider taking into account initial velocity in both X and Y, a starting angle of elevation, and a direction. The articles here and here provide ways of taking that information calculating the ball's position at any specific time, t, which is the time since the person hit the ball. They also allow you to calculate the angle required to hit the ball at to hit the target which could be useful to apply a random offset to for bots depending on their difficulty setting.

# Answer
> 1 votes
The golf game I wrote worked as follows:

In between shots (i.e. when the ball is not moving), the game is using a standard UI event model to allow you to place and execute your shot.

During a shot (i.e. while the ball is in motion), UI event listeners are turned off, and a standard real-time game loop is turned on, to resolve all physics -- motion, friction on that motion, and collisions. As soon as the ball comes to a halt, that physics loop is turned off, and UI event listeners are once again switched on, so the player can line up their next shot.

As Martin Foot has said, you want motion modifiers to your ball (damping from rolling along the green, and also collision checks and resolutions) to be applied every tick of your game/physics loop, typically between 1 in 20 and 1 in 60 times per second. If you have other movable obstacles, then you will include processing of these, here.

---
Tags: game-design, iphone, game-mechanics
---


title: Projected trajectory of a vehicle?

text:
# Question
Title: Projected trajectory of a vehicle?
In the game I am developing, I have to calculate if my vehicle (1) which in the example is travelling north with a speed V, can reach its target (2). The example depict the problem from atop:

There are actually two possible scenarios: V is constant (resulting in trajectory 4, an arc of a circle) or the vehicle has the capacity to accelerate/decelerate (trajectory 3, an arc of a spiral).

> I would like to know if there is a **straightforward way to verify if the vehicle is able to reach its target (as opposed to overshooting it)**. I'm particularly interested in trajectory #3, as I the only thing I could think of is integrating the position of the vehicle over time.

**EDIT:** of course the vehicle has always the capacity to steer, but the steer radius vary with its speed (think to a maximum lateral g-force).

**EDIT2:** also notice that (as most of the vehicles in real life) there is a minimum steering radius for the in-game ones too).

# Answer
> 15 votes
If you can vary your speed (thus your angle of steer) you will always find a solution, starting from the degenerate one where the entity is almost stopped rotating in a little circle until pointing the target.

If you can't vary your speed, you can think about unreachable areas or shadows that you can not reach even using your better steer, if the target is in those areas you cant reach it (unless "overshoot" you can even surpass them and put them out of the shadow area).

Your best steer let you to turn left/right on an arc of a circle, letting you to draw a complete circumference:

As you can see what is inside one of the two circles cant be reached directly.

A body of mass *m* that is steering over a curve with radius of curvature *r*, experiences a radial apparent Centrifugal force caused by the inertial behavior of the body, equal to:

where V is the speed of the body (the lenght of the velocity vector); being the acceleration of a body due a force being:

our acceleration is:

If we say that am is the maximum acceleration we obtain that:

where rm is the mimimum radius using the maximum acceleration.

When you want to test if the veicle in **P** moving at speed *V* can reach the target in **T** you have to:

1) compute **C1** and **C2** as:

2) test the miminum distance of **P** from **C1** and **C2** as follow:

If d is greater than rm this means that **T** is outside both the shadows and then is reachable by the vehicle simply adjusting the steer under the steer constraint. (to be more precise there is a path under constraints that let the function of distance between **T** and **P** be monotonically decreasing)

**\[UPDATE\]**

If it possible to change the velocity, is always possible to get an arc (i.e. a velocity/radial accelleration couple) that goes from **P** to **T**. This is possible because the radius becomes a truly degree of freedom.

This is a possible construction:

The black line is the axis where the center of circles may lay: it is perpendicular to the current facing of the vehicle and passes through its center of rotation.

The green segment represents the line that is perpendicular to the one that connects the center of the vehicle with the target and passes through the middle of that distance.

The green line crosses the black one exactly at the center of the desired arc. The length of the orange segment tell us the radius of turning that can be achieved by regulating the velocity and turning at maximum steer or regulating both the velocity and the steer to stay under the constraint

---
Tags: mathematics, physics, projection, trajectory
---


title: vertex array with smoothness

text:
# Question
Title: vertex array with smoothness
I'm using vertex array to draw 2d geometry, but I can't achieve smoothness.

This is the code I'm using:

```
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);

glColorPointer(4, GL_UNSIGNED_BYTE, 0, shared_colors);
glVertexPointer(3, GL_FLOAT, 0, shared_vertex);

glDrawArrays(GL_LINES, 0, shared_counter);

glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisable(GL_BLEND);

```

Some advice?

# Answer
> 2 votes
Simply use `glShadeModel(GL_SMOOTH)` when you want to smooth out the colors between your primtitive's vertices. The initial value is `GL_SMOOTH`, so if you haven't changed it, you'll probably don't need to set it.

If you want smooth lines, use `glEnable(GL_LINE_SMOOTH)`.

# Answer
> -1 votes
Quite some time since i had the pleasure to play with opengl, but one thing comes to mind: Is it not necessary to specify the normals if you want your smooth shading?

---
Tags: c++, vertex-arrays
---


title: How does UVW texture mapping work?

text:
# Question
Title: How does UVW texture mapping work?
I'm trying to understand the *mathematical* theory behind UVW mapping. Can anyone explain me how UVW mapping works? Or at least provide me a pointer?

# Answer
> 14 votes
This is the way I understand it. Could be totally wrong, but I'm sure someone will ~~flame~~ correct me if I'm wrong.

The mathematical theory behind UVW texture mapping is similar to the theory behind UV texture mapping.

See Bummzack's link here: What exactly is UV and UVW Mapping? to get a better explanation of what UV mapping is. Basically, you're mapping an area of a texture to an area of a surface. Interpolating the values in-between based on those mappings.

Same thing with UVW. Except now you're mapping a volume of texture to a volume of surfaces. Interpolating the values in-between. Now with the 3rd dimension you can warp a 2d texture to better fit an object.

Lets look how this is used in 3D textures. 3D textures can be created by layers of 2D textures, and interpolating the texels in-between. Visually a 3D texture could look something like this:

Where the "planes" in the R axis are 2D textures. If we were to set each layer to a different solid color, and apply this to a 3D object, we'd get something like this:

You can see how the solid colors have been interpolated in-between the layers. Here's the same type of thing, but with a landscape. Where from top to bottom, the textures could be: snow, rock, grass, sand.

Now if we're only using one R "plane" (one 2D texture), but mapping to 3D object? Obviously this doesn't give as much flexibility as multiple layers of textures, but it sure is a lot less work. However, just projecting a 2D texture onto a 3D surface is going to cause some issues. Think of the situation where you're shining a laser on a wall. At a perpendicular angle the laser point is nice and round. At any other angle, the point starts to stretch and skew. Same thing will happen when projecting a 2D texture onto a 3D surface. Any face that isn't perpendicular to the projection will be distorted. How do we fix that? By distorting the projection. Take the laser example, if we had a laser that when shone on a perpendicular surface it was stretched and skewed. When we shone that laser onto a angled wall the angle could "cancel" the effects of the stretching. **The 3rd dimension allows us to "shape" the projection so that it fits the surface we're aiming at.** For example, some kind of wavy 3D surface might have a texture like this (but not so crummy):

Like I said, this is just my understanding of it. I agree, there isn't much good information out there on this subject. Hopefully this (likely wrong) answer will prompt someone with more knowledge of the subject to speak up.

The images for the 3D textures came from this page: http://www.gpwiki.org/index.php/OpenGL:Tutorials:3D\_Textures

---
Tags: opengl, mathematics, textures, uv-mapping
---


# Question
Title: Setting up collision using a tilemap and cocos2d
I'm building my first platformer using cocos2d and a tilemap. I'm having trouble coming up with a decent way of determining if the character is colliding with an object. More specifically, in which direction is the character colliding with an object.

Following the tutorial here, I have made a separate "meta" layer of collidable tiles. The problem is that unless the character is in the tile, you can't detect the collision. Also, there's no way of telling WHERE the collision is occurring.

The best solution would be one that could tell me if a character is up against a wall, or walking on top of a platform. However, I can't seem to figure out a good technique for this.

# Answer
> 4 votes
first of all you don't need the character to be a tile, your character is basically some ccNode Object (it can be a sprite, a tile, an animated image or whatever) and every ccNode instance has a boundingBox (I'm not sure property or function) you can easily check if two bounding boxes collide or not. depending on your layer type you can use either one of these two sudo codes:

```
// if you have an object layer
    foreach(tile in layer->tiles())
        if (character->boundingbox.isColliding(tile->boundingBox()))
            report(collision);

// if you have a normal tile layer
    for(x = character->boundingbox->left / layer->tileWidth;x < character->boundingbox->right / layer->tileWidth; x++)
        for(y = character->boundingbox->yop / layer->tileHeight;x < character->boundingbox->bottom / layer->tileHeight; y++)
            if (layer->tileAt(x,y) == validTile)
                report(collision);

```

to find out from which direction was the collision generated you can easily check which way where your objects moving, just check their relative movement speed, depending on their speed they can only create collision in one direction. this way you can choose if a collision was made from up or down, or if it was made from left or right. to choose between up and left you have to use more complex algorithm. the base idea is to check which type of collision is possible and/or more likely. if two object have intersection in a 1px\*20px area you can assume they where already in a same above each other and then one of them fell down on the other object.

if you still didn't get what did I mean just put a comment and i'll try to explain better.

---
Tags: collision-detection, cocos2d-iphone
---


# Question
Title: OpenGL: Display Memory, Offscreen Memory, and the Framebuffer?
From my understanding, display memory resides on the GPU and is what's currently being displayed.

Offscreen memory resides on the GPU and is used for things that won't be displayed.

The framebuffer is graphics memory that is the result of OpenGL rendering.

So, how do these 3 correlate to one another? It seems that the framebuffer may reside in offscreen memory maybe? Is this true?

Any help in understanding all this would be helpful.

Thanks.

# Answer
> 2 votes
OpenGL does not have these concepts you are referring to.

There is the default framebuffer. This is a series of named images: the back color buffer, the front color buffer, the depth buffer, aux color buffers, etc. The front buffer generally represents what is seen in a window. You generally render to the back buffer and then use a buffer swap to put that data in the front buffer.

There are also framebuffer objects (FBO). FBOs can have user-created images attached to them. These can be mipmap levels of a texture or from a renderbuffer (a non-texturable image). Nothing you render to these images will be displayed unless you take additional steps.

# Answer
> 2 votes
There's also no memory partitioning on modern GPUs either (hasn't been for well over a decade) - it's just a single block of memory that the driver can pull down from for various uses as required. It's therefore meaningless to speak of different "types of memory" and which "type" a particular object may "reside in". It's all just video RAM.

# Answer
> 0 votes
Depending on your OS and video mode and drivers, the front buffer might be anything that your OS/Driver tells you it's the front buffer, it could be offscreen memory that the OS/Driver then copies to the actual "Display memory" if there is such thing in that particular video card.

OpenGL tries to create a framebuffer, but it relies on the drivers, and probably in the way the OS exposes them, so the OS or the Driver may well decide to handle your final image, for example to apply custom filters configurable from the control panel of the video driver. You can never assume that if you access the framebuffer you are pointing to the display memory. Most likely will be a pointer to the "offscreen VRAM", or some mapping for a memory closer of both the CPU and the VRAM such as the bus memory, which is far away from the display memory, if there is such distinction in the videocard in question.

---
Tags: opengl
---


title: Handling collisions with ground

text:
# Question
Title: Handling collisions with ground
How do you usually solve collisions between entities and the ground? Sending collision events hardly seems appropriate since almost everything touches the ground at almost all points in time. Calling collision handling functions doesn't sound any better.

How is this normally achieved? Is handling of slopes significantly harder?

# Answer
When you detect a collision with the ground and the speed Y is low, you disable the gravity for that object, set the Y speed to 0 and skip the collision reactions against that floor (store a temporal reference to it) until its Y axis acceleration gets disturbed somehow (because of an external force such as a collision reaction or the character jumping or the floor getting out of range).

You can have many floors then you know that when you are over one floor you don't have to check collision against others, you only check for collision with the floor you know you were last frame, and if you don't collide with it then you wait until a floor object reports its collision and you can start the process again.

EDIT: I forgot to mention that if you're dealing with more realistic physics such as rigid bodies, checking the Y speed may be not enough for non-spherical objects (non-circular in 2d) as an angular velocity may affect your vertical force depending on the shape and momentum of the object.

Note that by identifying the ground objects you can exploit their mutual exclusivity properties in many ways, such as for collision with other objects (an object over a floor doesn't collide with objects that rest over another floor) similar to the way a quadtree works. You may also find place for some prediction there, depending on the rules of your game (more realistic physics will always be harder) you may be able to predict the floor where your object will (most likely) be next, then set that floor as a priority for ground collision checking.

Ah, and for if handling slopes is harder, it depends on the variety of angles for all slopes (in some games the slopes are *always* 45 degrees or so) and on the way you make your objects slide over a ground, ie you may want that if the Y velocity is high, you slide when falling on a slope, but if your Y velocity is low enough you could stop it. You may also want to add an effect to have different floor materials, so you would slide less over grass than over polished metal.
> 4 votes

# Answer
I'm not sure if any one else used same algorithm or not but for an adventure game we were developing we used a hidden polygon shape which specified ground level (and also some forbidden places). for each object we used a raycast directly toward a ground from that shapes center of mass and then picked ground polygon. in the last step we were only adjusting object altitude so that lowest object part be over ground level. in that algorithm we also checked if the first polygon picked was from forbidden area, we just reversed last movement, and it worked so well. you can also easily implement stairs and multiple ground levels with this algorithm.

the main positive point is you can ignore most of complex 3D Object collision and ground collision computations (by creating a moving forbidden area under every entity) but it almost doubles the work your level designers need to do.
> 1 votes

---
Tags: architecture, collision-resolution
---


# Question
Title: Convert Autocad DWG to OBJ, FBX or similar
I know this is only partially game development related, but couldnt find another place to ask.

How can i convert an autocad dwg or dxf file to a more 'common' format like OBJ, FBX, 3DS, etc. ?

i tried directly using autocad LT but the export options dont have any other format.s

free and oss solutions preferred.

# Answer
Try 3DSOUT

1. At the command prompt, enter 3dsout.
2. Select objects in the drawing to export.
3. Press ENTER.
4. In the 3D Studio Output File dialog box, in the File Name field, enter a file name.
5. Click Save.
6. In the 3D Studio File Export Options dialog box, select or change the necessary options. (See the 3DSOUT Reference below for more information about these options.)
7. Click OK.
> 4 votes

---
Tags: 3d, file-format
---


title: How are voxel terrain engines made?

text:
# Question
Title: How are voxel terrain engines made?
A few days ago I found something called voxel terrains and I think that they're pretty cool. But I don't know anything generating them. Do you model it in your modeling software or use something like a heightmap? I read on wikipedia that voxels are like 3d pixels or volumetric pixels.

After I make the voxel terrain, how can I take these voxels and make them **destroyable/diggable**?

I will pick the best answer based on:

1. **code and algorithms.** preferably based in C#
2. **explanations.** I am a beginner with algorithms but I'm very familiar with object oriented programming
3. **step by step demonstrations.** Not only concept but direction.
4. **diagrams/illustrations.** No, not screenshots of other engines.

I know that this is a complicating subject. But, thanks for any help!

No, I'm not trying to make a minecraft clone.

---

## Edit

Thanks to everyone for your great help (especially Nick Wiggill)! This is what I managed to make (Work in progress).

# Answer
**To generate a voxel terrain**

**(a)** A common method is to generate a heightmap using Perlin noise. A heightmap is basically a monochrome image representing different heights by the darkness or lightness of its pixels.

You'll look at individual pixels in this heightmap to create "stacks" of voxels up to different heights (z-axis) in different (x,y) locations, according to the brightness of that pixel in the heightmap image. Because a Perlin noise image is smooth (no sharp edges of light against dark), you will have smoothly rolling terrain as a result.

**(b)** You can construct it incrementally by creating the landscape out of different polyhedra. Create a polyhedral vector shape that approximates the voxel shape you want. Using any 3D-point-in-polyhedron method (most often, point-in-convex-hull), check which points of your world grid fall within that polyhedral volume. For example, define a pyramid in space. After checking every point in the local region of your world space against that pyramidal volume, you will know which points fall within it, and you can set those cells as "present" meaning they become voxels rather than empty space. You now have a voxel pyramid in your space. You can continue to add shapes of any sort together, in this way, until you have formed a terrain.

**(c)** (Really the same as **b**) Write a modelling tool. Voxatron show how this would look. This is just creating the voxel forms in a substitute world (the editor) and then importing these into your actual runtime game world. I believe Voxlap had the first open source editor for voxels. You can place individual voxels, or you can use a voxel "brush" with different shapes / volumes to draw voxels into your world.

---

**What you'll need to construct your own voxel-based game**

I include this section because the voxel road is not an easy one, at least not at present. Lately, a lot of research is once again being put into voxel engines by the big players, toward rendering and physics applications.

**Simplicity** may be a problem, because dynamically constructing a world out of raw voxels is a procedural approach to world construction and this **not inherently simple**. So sorry, there are going to be a few technical terms here. Writing a voxel engine is a pretty serious undertaking and requires knowledge across multiple areas of game engine development, particularly in terms of spatial concepts, and this means understanding 3D vector math, matrices and basic calculus to some reasonable level.

Having said that, your "generation of a voxel terrain" requires a context in which to work, since voxel engines aren't exactly widespread. Lets proceed to a basic description of how a voxel engine works.

Voxels are the basic building blocks of your world. Their positions are defined by an integer-indexed 3D grid (array) rather than a continuous floating-point space (as used in vector-based 3D games). These will be the "atoms" of your world. They could be 3 feet high as in games like Minecraft, or they could be smaller than your virtual character's eye could actually see, unless clustered together in large numbers -- a bit more like molecules. There are two kinds:

* Cubic mesh based voxels (example) -- these are a newer sort, used for simplicity and easily usable in conjunction with modern graphics tech. Used in games like MineCrat and Dungeon Keeper.
* Point voxels (example, example) -- the original voxel. Each is an individual, collidable point in space, although it may be surrounded by a spherical bounding volume. They are simpler, so you can have many more of them in your world, and you can thus make them smaller, which is generally favourable. Two games that used these were Comanche and the 1990s remake of Lords of Midnight.

Either way, your approach to manipulating voxels in your world is much the same, as follows.

To construct and move objects in your world, you will need the mathematical tools mentioned above. For example, to create a wall: Construct a box of the appropriate dimensions in 3D space, using vectors. Use matrix math to transform your box to the rotation and position you desire in your 3d world (in continuous vector space). For a voxel engine, the additional step is to now use a 3D point-in-polyhedron algorithm to determine which of your voxels fall inside that rotated space.

Essentially, this is the way you would construct most objects in your world. Beyond that, you could write your own tools to "model" a character in the way you might in say, Maya or 3DS Max. But since you are modelling you character out of voxels instead of points, edges and faces, your methods will be substantially different. If you decided to then rotate these objects in your world, you would need to similarly use matrix transformations to do so.

Destructible terrain is as simple as either removing one voxel at a time according to some method of your choosing, or using CSG (Constructive Solid Geometry) operations on large volumes of voxels to remove them according to some predefined volume; for example, if shooting a laser beam through a rock, you might use a cylindrical volume to subtract the voxels here the beam is shooting through the rock. CSG is a relatively simple process using the 3D spatial grids which form your voxel world, and checking every cell in a section of a base grid (in this case the rock) against another grid (in this case, the laser beam)

In order to have material "flows" (as Vigil hinted at in his comment on sand), you will need to look into fluid dynamics and cellular automata. These were used by the author of Dwarf Fortress, Tarn Adams, in what is essentially also a voxel world (albeit the voxels are much larger in this case, comparable to Dungeon Keeper, the principle remains the same). These are cutting edge topics and not a necessity for voxel engines as defined, so I will leave this as a "stub" for your own research.

CSG and fluid dynamics bring me, lastly, to optimisation. Voxel engines currently in development almost exclusively make use of sparse voxel octrees (SVOs) which is a method of subdividing voxel space to varying resolutions, as evidenced in this video showing off the upcoming Atomontage engine. Using octrees/SVOs is more of a necessity than an optimisation choice, because of the processing overheads involved in processing one massive, uniform grid. An octree is essentially an tree (directed acyclic graph) where every node has either 8 or zero child nodes depending on whether the space it represents contains any physical volumes. Diagrams showing how octrees subdivide space to form voxels are here.

The best open source voxel implementation I know of is Ken Silverman's Voxlap Engine, which was used for Voxelstein3D. It is written in C++, and implements CSG operations for terrain deformation.
> 60 votes

# Answer
The best way to generate interesting voxel terrain is with a Perlin noise density map. Rather than using a 2D Perlin noise map defining the height of a 3D world, use a 3D Perlin noise map. Weight the map so that the values closer to the bottom will be more likely solid, and the values closer to the top will definitely be air. This gives your world height, but also allows for overhangs and caves, similar to Minecraft terrain, as this side-view of a slice of terrain shows:

From here you can test for floating islands, or add cave systems using fractal noise:

The above pictures and cave system ideas are from this excellent blog post. You can learn all about Perlin noise here, and there is some sample code to get you started here.
> 34 votes

# Answer
The other answers here are excellent, but I took a slightly different approach.

I generate an environment in a modeling tool (3DSMAX), and build a sparse octree from it. Each cubical, non-empty leaf node is a voxel. At render time, I use raycasting (implemented in HLSL) to find which voxel occupies which pixel, and set the pixel to the color stored in the node, which I calculated when generating the tree by averaging the texture values from the source model.

This gives you a lot of nice benefits - collision detection for free, variable LOD, view space culling, etc - and, aside from the raycaster - its easy to implement.

Unfortunately, it's near impossible to post sample code from a phone.
> 5 votes

---
Tags: procedural-generation, terrain-rendering, voxels, csg
---


# Question
Title: Why do games run so much better in Windows than in OSX?
For example, on my Mac Mini with Bootcamp, Team Fortress 2 runs at about 20fps in OSX and 80fps in Windows. This seems to be a common case. Why is this?

# Answer
> 15 votes
Direct3D drivers on Windows are ridiculously optimized, sometimes for specific games, and developed by individual hardware vendors.

Apple's OpenGL drivers are written and maintained (AFAIK) by Apple, and are intended for "general" OS use, compositing the UI and whatnot. There's no so much optimization for gaming and high-performance throughput.

Basically, a *lot* of resources from a *lot* of sources have gone into making DirectX fast on Windows, while much fewer resources are available to do the same on Mac.

# Answer
> 13 votes
While I won't discount the optimization that Microsoft may have put into Windows and/or DirectX, I strongly believe that most programs perform better on Windows simply because that's what the developers focus on (that's where the money is). They make design decisions with Windows in mind, and then later try to make it work in other OSs (Mac, Linux, etc.). I constantly run into this at work: other projects have so much trouble with porting to non-Windows systems because the developers treated it as an after-thought. I have repeatedly written programs that build on multiple OSs with very little effort because I planned it that way from the beginning. Once you've really tried to do it (as opposed to grudgingly doing the port after-the-fact), you learn what it takes and it requires very little extra effort. Most of the performance differences are caused by design decisions made at the beginning of the project.

# Answer
> 7 votes
As a fellow Mac user, I'd like to offer an additional factor: the CPU scheduler in OS X is more "fair" than in Windows.

This is sort of a complicated computer science topic, so here's a simple way to think of your CPU scheduler: your processor has to juggle many tasks at once (all your open programs, plus background system processes). It can only *actually* do a couple things at once (the number of cores times the number of threads per core; a dual-core i7 can do 4 tasks at once, for example). So it splits all the work into pieces, and alternates between them so that it looks like it's actually doing a lot of things at once. When you run two programs, the processor is actually just alternating back and forth between processing those two programs, *really* fast (like, a few microseconds here, and then a few microseconds there).

The pattern for which things are executed in what order and for how long is decided by a "scheduling algorithm". For example, the round robin scheduler just arranges the tasks in a circle and processes each one in order. Another scheduler might arrange the tasks from least-to-most time remaining - small tasks would be done quickly, and big tasks might have to wait a while before being done.

Windows and OS X are very different, and their scheduling algorithms are a bit different as well. Windows is a little "smarter" about prioritizing things, so it gives extra priority to visible programs in order to make the computer appear faster. OS X, however, is more fair to background processes. The overall algorithms are much the same between the two OSes (they are both *multilevel feedback queues*), but this little detail results in a different user experience.

Both sides have their advantages. Like I said, visible programs in Windows will appear faster because they get more priority; but if one visible program decides to take a lot of power, the whole computer suffers a bit more. OS X's more fair scheduler results in more predictable and stable speeds, which is good for audio and video operations. For example if you're playing a song in the background, it's less likely to stutter when you do other things at the same time than in Windows.

**So, the takeaway point is this: a full-screen game in Windows is going to get high priority on the CPU and anything running in the background will just have to wait. In OS X, this is less the case.**

Some technical info about the schedulers is given here; the rest of this answer is from my computer science education and my usage of OS X over the past 10 months, after having used Windows for over 10 years (and Linux occasionally). I am sometimes frustrated by the more fair scheduler, but other times I appreciate its advantages.

Linux, by the way, has an even more fair scheduler implementation; this is what makes it a great server, but in my opinion the user experience is degraded. For example, when your computer is bogged down with tasks, your cursor will stop responding smoothly because it's given the same priority as everything else. This basically never happens in Windows or OS X.

# Answer
> -1 votes
*Some* games that have been "ported" to MacOSX are actually *Windows* games running within an emulator. While I don't have a complete list of examples, it seems that there is at least SPORE that was like that:

> SPORE was never officially released on GNU/Linux, and the Mac version aged poorly. The Mac port is actually the Windows release packaged with Cider, which is a depreciated technology wrapping a (now old) version of WINE around games. (Source)

Running a software within an emulator is by definition slower than running it natively.

---
Tags: performance, windows, macos
---


# Question
Title: Video game entity storage and structures
I finally have all the working input/output of a game engine.

However, I'd like to be able to put an amount of about 2000 shots being simulated in a region, total. I have done other games where all the data was stored in a linear array and iterated every turn, and referenced by index number. This method seems to be fast enough, grants random access instantaneously and I'd say it "just works". However, inserting a new element requires searching for an empty space, and iterating over the "inactive" shots.

Considering the amount of max shots, what would be the best approach to this? Am I thinking too much about this, perhaps, and the array is a good enough system?

The engine works in C99. Shots will be destroyed when out of "practical" range and collisions will be done around the player rather than the entire working map. The game is real-time action style so updating needs to be quick, and shots might need to be accessed by position, which is another weakness of the array approach (unless I add that information to "slices" of the main map, I guess).

To summarize. What would be the best data structure in terms of insertion speed, allowing random access and iterating without gaps? A name, if it exists, would be enough.

# Answer
> 1 votes
I don't think you can find anything other than "array" if you want random access power. "Hash" could be it but using "hash" for saving shots doesn't seem to be right. I would stick to "array" but change the way of finding empty or inactive slots.

The way I used for my game is

1. Define one indexFirstEmpty pointing to the first empty slot.
2. Insert a new shot into the first empty slot and increase indexFirstEmpty .
3. Delete a dead shot by swapping it with the last valid shot ( slot\[indexFirstEmpty - 1\] ) and decrease indexFirstEmpty. Don't forget to check valid range and self swapping.

With this way, you don't have to iterate the array to find an empty slot. This works because I don't care the order of shots in the array as long as they are partitioned correctly. If you want to keep the order of shots, you need a different way but it will be slower than the one I suggested. Good Luck!

# Answer
> 0 votes
Can you move stuff around in your array? Something I've done in the past to keep items packed (when the exact sequence is irrelevant), is whenever you delete something out of the middle somewhere, relocate the last element of the array into the empty slot. This keeps the storage tight, so you can always add a new element at the end in O(1) time, without worrying about all kinds of holes.

Another thing you can do is add a field to the struct (assuming your array is an array of structs) to implement a singly linked list for the "empties" in the array, in this case, the new field is the array index of the next element in the list. Now, it's a singly linked list, but you use it like a stack; always add to/remove from the head end. You keep another int that indexes the first element in this free-elements list, so you can always allocate an empty slot in O(1). Whenever you free a slot, you set its next-element index to the current head of the free list, and change the head to index the just deallocated element.

# Answer
> 0 votes
All 3 suggestions sound pretty good. I am mostly inclined towards Young's and Quasiverse's answers (I think with a stack). JustJeff's answer is also quite interesting, and I might use that one for other type of entities.

On second thought I might not really need to keep track of the shots in exact order although the order-aware answers are still certainly useful.

Thanks a lot everyone! Unfortunately because the post was moved (honestly didn't know there was a whole game dev Stack site....!) I cannot pick any of the answers, sorry about that.

---
Tags: c
---


# Question
Title: Algorithm for a tool to theorycraft stats based on a game(league of legends)
I would like to create a simulator(basically for testing purposes) for a game(League of legends).

The basics of the game:

you have a hero which has some stats:

* Health Point
* Attack Damage
* Attack Speed
* Armor
* Armor Penetration
* Movement Speed

Hero can have 4 skills(you get one skillpoint at each level) (They are activated manually, most of the time, has cooldown, damage, attackpower/attackdamage scale ratio, and skill level) \+ a passive skill

You can kill enemy heroes, or neutral monsters, they have the same stats:

* Health Point
* Attack Damage
* Attack Speed
* Armor

What I would like to do:

Create a tool to test if a particular item, or a particular stat increase would speed up your killing power/speed.

map: http://evtron.com/Evtron-Alpha/wp-content/uploads/2011/02/Summoners-Rift.jpg

Stat examples:

* Hp: 420
* Ad: 55
* AttackSpeed: 0.613 ( attacks / s -\> every attack at 1/0.613 s)
* armor penetration: 25

The character gonna autoattack the enemy with the 1/attackspeed, and damaging with attackdamage(there is a formulate to calculate the damage, but thats not important in this phase i guess), once they are dead, moving to the next one with movingspeed(you can see the camps on the map, the yellow skulls)

I was thinking about the algorithm:

1. I thought if i just make a for from i=0 to i=30000(counting ms), so I can just check the enemy hp and my hp as well at every ms turned out so bad(pretty cpu heavy, and i would like to put some random in it, so i should be able to sum up 1k iteration, which is impossible)
2. Secondly, i thought i should just do a for from i= 1 to 30, and check every second, and check what happened in the last second, but some of the neutral monsters are in a big camp (up to 4 monsters), and this way the code was getting complicated and complicated.
3. I'm gonna create threads for each player/monsters, and once they finished look up when they died, and reduce the hp of the player.

My question, is this the right way to go?

TLDR: I would like to create a tool to create analysis(iterate 1k and calculate average) about a game which stat increase would make the character killing faster neutral monsters.

I would prefer java, but atm I'm stuck at the algorithm.

---

@Karoly S: Yep, it' my bad, .com -\> .eu

I've been working on this:

I'm checking the remaining time on each object(player skill, autoattack, buffs), and always pick the shorttest time, and store the last\_time, and add the time to time, at the next round I calculate the time by (time-last\_time)

If the object has remaining time 0, it will do whatever it needs to do.

I don't know if it's effecient way or not, but that's the best I could do.

# Answer
Alternatives to frame-by-frame simulation:

You can get kind of a reasonable approximation for simulation by a formula such as

```
rawDamage = <some function of strength?)
Damage = rawDamage - enemyArmorReduction
DPS = (attackSpeed * Damage) * enemyArmorMod
myRemainingHP = myDPS / theirHP  - theirDPS / myHP

```

You can also maintain a move-queue, so that you simulate per-move, not per-tick:

```
// my aspd = 4 attacks per second, his aspd = 3 attacks per second
0.0s : start battle
0.25s: I attack
0.33s: He attacks
0.50s: I attack again
...
1.00s: I attack
1.00s: He attacks
...

```
> 1 votes

---
Tags: algorithm
---


# Question
Title: How do I get the vertical angle between 2 vectors?
So I'm modding a 3D game, my goal is to place a label on the screen pointing to the unit's direction. I'm getting the horizontal angle by projecting these vectors in a plane, like this:

```
private double getXAxisAngle(EntityPlayer player,EntityPlayer player2){

    double meYaw = player2.rotationYaw;
    double meX = player2.posX;
    double meZ = player2.posZ;
    double playerX =  player.posX -meX;
    double playerZ =  player.posZ-meZ;
    double yawX = Math.cos(Math.toRadians(meYaw));
    double yawY = Math.sin(Math.toRadians(meYaw));
    double dist = getDist(playerX,playerZ);
    playerX = playerX / dist;
    playerZ = playerZ / dist;
    dist = getDist(yawX,yawY); //get the vector magnitude
    yawX = yawX / dist;
    yawY = yawY / dist;
    double angle1 = Math.toDegrees(Math.atan2(yawY, yawX));
    double angle2 = Math.toDegrees(Math.atan2(playerZ, playerX));
    double angle = angle1-angle2;
            angle+=90; //So when it's facing the other unit it becomes 0
    if(angle > 180)
        angle-=360;
    else if(angle < -180)
        angle += 360;

    return angle;
}

```

This function gives me an angle between `0/-180` and `0/+180`, depending on which side I'm facing then I get this angle and transform into a coord into the screen like this:

```
private double angleXToPosition(double angle,FontRenderer fontrenderer,String label)
{
    ScaledResolution scaledresolution =
        new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);

    double width = scaledresolution.getScaledWidth();

    double namePosX =
        (int)(angle * ((width / 2 - (fontrenderer.getStringWidth(label) / 2)) / 50)) +
        width / 2 - (fontrenderer.getStringWidth(label) / 2);

    //If the angle is bigger then 50 the label sticks on the side of the screen
    if (angle > 50)
        namePosX = width - (fontrenderer.getStringWidth(label));
    else if (angle < -50)
        namePosX = 0; //Same as above

    return namePosX;
}

```

And it works until this, the label moves perfectly to the sides, accompanying the unit position on the screen, but now I'm trying to make the label move up and down and the same functions doesn't work, and I can't figure this out.

**Some info:** the pitch of the player when facing the sky is `-90` and when facing the ground is `90`.

# Answer
> 1 votes
first of all I'm curious about this part :

```
double namePosX =
    (int)(angle * ((width / 2 - (fontrenderer.getStringWidth(label) / 2)) / 50)) +
    width / 2 - (fontrenderer.getStringWidth(label) / 2);

```

are you sure you have to multiply angle by some value? we usually first compute sin or cos of the angle!

after that I suggest you change your angle computing functions to these ones (it's just a sudo code):

```
void getAxisAngle(EntityPlayer a, EntityPlayer b, out double yaw, out double pitch)
{
    double deltaX = a.posX - b.posX;
    double deltaY = a.posY - b.posY;
    double deltaZ = a.posZ - b.posZ;
    yaw = atan2(deltaY,deltaX);
    pitch = asin(deltaZ / sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ));
}

```

both `atan2` and `asin` are already defined in math libraries so you just have to find them in your standard language library. there is a slim chance that you can't find `atan2`, if that's the case you have to create your own version of `atan2` using atan.

sidenote : * atan = arctangent * asin = arcsine

---
Tags: vector
---


title: GNUstep Game Development

text:
# Question
Title: GNUstep Game Development
Are there any good resources out there for game development in GNU step? I looked at some of the source code for ooLite, but that didn't really have much in Objective-C.

What is there these days?

# Answer
> 1 votes
There is an effort to make a cocos2d-iphone compatible that uses the gnustep library: cocos2d-GNUstep You may find it useful but only if you plan to develop under linux and compile using mac...

---
Tags: objective-c
---


# Question
Title: What would be the best way to find an open space in a level?
I'm working on a 2D game where you use paint to add tiles to a level and right now I'm working to add warp tiles. I have it set up so certain direction-oriented paints use two points (a start and end) to determine which direction the tiles will point (left, right, up, down.) The warp tiles have these points, but they'll be added to two other lists (warp start and end). The way the warps work is: if the player hits one tile they'll be teleported to the corresponding warp tile. Now, if I'm going to get this to work properly, I need to make it so the player can't be teleported into a wall or off the map. So I need to move the point to an open tile exactly one space away from any walls.

What would be the best way to do this?

# Answer
If all you want to do is ensure that the clicked on tile has open tiles around it, I would just create a function that checks the tiles around it. And then call that on the clicked tile.

You could set it up in a (nested) loop or just create if statements for it. So, in pseudo-code:

```
function IsTileOpen(tile)
  if tile NOT open
    return false because if the clicked tile isn't open, why check any others
  if tile on top row
    return false because we're against the top wall
  if tile on left column
    return false because we're against the left wall
  if tile on right column
    return false because we're against the right wall
  if tile on bottom row
    return false because we're against the bottom wall
  if top left tile NOT open
    return false
  if top tile NOT open
    return false
  if top right tile NOT open
    return false
  if left tile NOT open
    return false
  if right tile NOT open
    return false
  if bottom left tile NOT open
    return false
  if bottom tile NOT open
    return false
  if bottom right tile NOT open
    return false
  return true because all the surrounding tiles were open
end function

```

**Edit Based On Comment**

There are two ways you could handle the situation:

1. (Easiest) You can just play a sound and indicate that the position they chose is invalid and they need to choose another option.
2. Use a search algorithm to find an open tile. However, I think there should be limits on how you use this. Take, for example, a situation where they click on the left side of the map and the only open spot is far on the right side. Your search algorithm finds that open spot and places the other warp there. This does not seem very intuitive and may be frustrating. My suggestion in this case (assuming you don't want to do #1 which is my main suggestion), is to only search the tiles around the current tile (perhaps in a n-tile radius). This way the warp gate won't appear too far from where you clicked. To do a search like this (assuming a 1-tile radius), you just need to call the function above on the eight tiles around the current one (assuming the current one wasn't available). You could do this in a loop or, again, with if statements.
> 3 votes

# Answer
I think you will need to find the nearest "free" rectangle to a warp tile, where the player can fit.

There is a similar question on stackoverflow. Click to see.
> 0 votes

---
Tags: xna, c#, tiles
---


# Question
Title: How do i get the X,Y and Z of the way my unit is facing?
I have the yaw and pitch of my unit at my disposal, I know if I use polar to cartesian conversion I'll get the X and Y of each one of those two, but I need them combined to give me the x,y and z of the direction I'm facing.

# Answer
> 2 votes
~~If you're using a regular Unity GameObject, you can just use `transform.forward` to access the forward direction of your object. See the Unity documentation for details.~~

~~If you're using a different way to track your object, Spherical coordinates are essentially polar coordinates expanded with a third dimension.~~

EDIT: I assume in Minecraft `z` is the vertical axis and `x` and `y` are on the horizontal plane. If this isn't the case, the principles would still apply but the `x`, `y`, and `z` would need to be assigned differently:

The `x` and `y` directional components can be determined from the yaw fairly easily: `x = sin(yaw)` and `y = cos(yaw)`. I'm not familiar with modding Minecraft to know whether or yaw is in degrees or radians—you may need to convert it in order to get real results from those trig functions. It's also possible that you may need to add a constant to the yaw to match the actual axes in the game (like adding or subtracting 90° to align with the world axes).

The `z` component can be determined from the pitch: `z = cos(pitch)`. Again, you may need to convert between degrees and radians or add a constant to match world axes.

# Answer
> 0 votes
If you have the Yaw and Pitch giving you the X and Y, can't you just assuming your roll (Z) is 0? Most game characters don't allow you to rotate on that axis.

---
Tags: 3d, coordinates, minecraft-modding, modding
---


# Question
Title: animation in Rhythm game similar to Jubeat Plus
For a school assignment I am planning to make a game similar to Jubeat Plus on the iPad. Right now, I have a counter that gives me each 16th note of a beat, I am reading out a Property List where I defined the time of each button when it should be pressed.

But I don't know how to add the animation. When a button should be pressed, the animation must be at some point already, whether it's a hit animation or a falling dot.

Can someone help me out please? even a feedback whether I'm doing this right or wrong

---

I don't know if i'm thinking at the right way Do I need to use the beats per minute, to calculate the seconds per beat. When this time is near my animation time I use the frame rate to animate my animation

Please correct me

# Answer
> 1 votes
Well a solution would be to convert your beats to a time stamp. So a note that occurs on beat X in a song that's Y BPM would need to be hit at time (seconds) Z.

From there it's pretty simple to figure out when you need to start doing things. If you're doing your standard Guitar Hero/DDR style "highway" for notes, and going from the start of the highway to the bar that signifies when you need to hit the beat takes constant time W, then you need to spawn your note object in the world at time Z - W.

---
Tags: cocos2d-iphone
---


# Question
Title: How fill gutter using ID3DXTextureGutterHelper interface?
> Using UVAtlas (Direct3D 9) Packed charts are separated by a user-specified gutter width. The gutter width is the amount of separation between charts, and allows for bilinear interpolation and mip-mapping to avoid rendering artifacts at chart boundaries. D3DX provides an interface for automatically filling in these gutters - see ID3DXTextureGutterHelper for more information.

How I can do that? I call ApplyGuttersTex, after calling ResampleTex but nothing changed.

# Answer
> 1 votes
There was a code sample on the subject, I've seen it some time ago, just can't remember where. Anyway, I guess you have already called D3DXUVAtlasCreate and got your new mesh with UVs for the optimized version of the original texture. Let's call it UVAtlasMesh.

Well, rest of the stuff is relatively simple. Just as one of your links says, gutter helper needs its mesh's D3DDECLUSAGE\_TEXCOORD 0 to contain new set of UVs and D3DDECLUSAGE\_TEXCOORD 1 to contain original set of UVs. So check that declaration of your mesh have both of these texcoords. Then the general idea is as follows:

1. Prepare a mesh with those 2 texcoords — just clone the mesh you got from AtlasCreate, so it will be your `clonedMesh`. Original mesh (the one you passed to AtlasCreate) will be called `originalMesh` in the same imaginative fashion.
2. Copy UVs from `UVAtlasMesh` to `clonedMesh` into D3DDECLUSAGE\_TEXCOORD 0.
3. Copy UVs from `originalMesh` to `clonedMesh` into D3DDECLUSAGE\_TEXCOORD 1.
4. Create a blank texture with same width, height and format as the original mesh texture, it'll be called `optimizedTexture`.
5. `D3DXCreateTextureGutterHelper(originalMeshTextureWidth, originalMeshTextureHeight, clonedMesh, gutterSize, &gutterHelper);`
6. `gutterHelper->ResampleTex(originalMeshTexture, clonedMesh, D3DDECLUSAGE_TEXCOORD, 1, optimizedTexture);`

Scrap clonedMesh and save the optimizedTexture. If it will look blank, recheck everything related to the D3DXUVAtlasCreate and its returned mesh's UVs.

---
Tags: directx, textures
---


title: Nvidia Cg 3.0 Manual/Documentation?

text:
# Question
Title: Nvidia Cg 3.0 Manual/Documentation?
I can only find a user's manual for Cg 1.4 from Sept 2005, and the Cg Tutorial from earlier than that. Cg is now on version 3 and I'm wondering about all the new profiles and tech that must be in it... Anyone got some links?

# Answer
The reference manual is up to date in the nvidia site Cg 3.0 Reference Manual, which i believe is where you can get most of the information you want. It does contain very detailed data of everything you can do with Cg, I don't think there's something missing there, but it may be hard to read at first as it's just a reference for all the technical aspects of it, you will hardly find something like a tutorial in it, perhaps there is some very small examples to explain some concepts (I'm gonna read some now it looks interesting).

EDIT: The manual doesn't seem to be that tough as I expected, if you have some experience with Cg or something similar already. I downloaded everything from the Cg Toolkit Download page. There it also mentions the users manuals and the demo tutorials were not updated, I believe you may find more updated tutorials on the web.

and this is The Cg Tutorial book, it may be useful for people interested in Cg
> 2 votes

---
Tags: documentation, cg
---


# Question
Title: In FPS's what is the primary reason for unused ammo in a removed magazine returning to the ammo pool?
All FPS's I know of return unused ammo in a removed magazine back to the users overall ammo count.

For example, I have 3 magazines with 30 rounds in each, I fire off 25 rounds and do a magazine change. I do this another 2 times so i technically have 3 magazines with 5 rounds in each, but when i reload I have a magazine with 15 rounds, somehow they have all jumped into the one magazine.

Yes, I am overthinking it and it probably wouldn't be fun. I'm just trying to narrow down the reasoning, especially games like modern warfare 2 which in terms of weapons are pretty much accurate in every other regard.

# Answer
There is a similar concept in many games; that you don't have to explicitly do every little thing. Some things can be assumed, ie. unless you are literally under fire all the time, you will have time to consolidate those 15 rounds into a single magazine. The fact the game doesn't show this is for the exact reason you've already highlighted: sitting down and moving ammo around isn't fun. Shooting things is.
> 7 votes

# Answer
Realism isn't always the primary goal in game design. Often it's providing the maximum fun possible. Having said that, it does seem a little odd that shooters like S.T.A.L.K.E.R. CoP do this, and then make the ballistic system very realistic in all other regards.
> 11 votes

# Answer
I agree with all here that it won't be fun to watch the guy reload his magazines - however, maybe there could be a system where you have, say, 5 magazines, and when you are not engaged in combat, you reload those automatically. While in combat, those are the ones you have, and so be it. Something like Metro 2033, where you have to pump up the air powered rifles, and quickly get into the habit of doing so when not actively fighting.

There are some games where you do lose the remaining ammo in the clip - see the list at http://www.giantbomb.com/realistic-magazine-management/92-2543/
> 5 votes

# Answer
Having asked this very question to a student team building an FPS, their answer was that they wanted to reward "prepared" players who reloaded often (making sure they had a full clip before going into a big fight). If they lost 3/4 of a clip every time they reloaded, that'd be, in design terms, punishing them.

Ultimately, it was s a result of design balancing to sacrifice a minute element of realism for the sake of rewarding player choices.

*THAT BEING SAID* there are a few games where you lose the clip each time you reload, meaning the player has to choose between having a full clip readied and losing ammo, or preserving bullets but only having 1/2 a clip. This seems to be more suited to survival/horror style gameplay rather than action.
> 4 votes

# Answer
In those situations the games in question aren't going for realism. Instead they are simplifying the game for the player by not punishing the behaviour of reloading too soon.
> 2 votes

---
Tags: game-design, first-person-shooter
---


# Question
Title: Creating similar effects of Geometry Wars in 2D only
I want to create a game with similar effects to that of "Geometry Wars"... for those who have never played the game, basically, massive amounts of 'bending' and 'warping' effects are done on the background during explosions and pulses.

Here is a picture:

The grid is normally a bunch of squares (perfect squares) in a perfect grid. When certain effects happen, the grid stretches and creates amazing effects.

Now, I'm trying to create a game using my own, from scratch, 2D engine. Is it possible to fake 3D effects such as this to my sprites? Is there some kind of effect I could do to do this?

# Answer
> 5 votes
I implemented this using a very simple physics system in Flash about 5 years ago.

From memory:

## Basic Structure

The grid is an intangible background layer. It can be affected by other physical items, but cannot affect them.

Every physical entity has a "gravity warp" factor. Blackholes are strongly negative (they pull the grid towards them), bullets are slightly positive (they push the grid away from them), the ship is Strong positive, etc.

The background grid can be considered a series of lines connected by a square grid of nodes at the joints. These nodes have a known orignalPostion, a resistance value (for spring physics), and of course their current position and velocity.

---

## The Nodes

Once per pass (typically once per frame for smooth results), for each physical entity that has a non-zero gravity warp (I used a registration/deregistration on spawn/death system to prevent extraneous iterations), for each of the nodes that are within a given radius of effect, calculate their pull by a simple formula such as `PullVector = NormalisedDirection * gravityWarpFactor / (Distance*Distance)`
Where:
`NormalisedDirection` is a normalised vector (magnitude = 1) indicating the position of the object relative to the node.
`gravityWarpFactor` is the previously mentioned Gravity Warp unique to each type of entity `Distance` is the scalar distance between the node and the entity.

By sum of all pull vectors on a given node by all nearby entities will give you the overall force being exerted upon it.

Then, for each node, you can use basic spring physics to move them from their current position in the direction they are being pulled, while providing resistance. They WANT to return to their original position, but constant force can pull them away. (Like tugging on a rubber band)

---

## The Grid

Once you've calculated the position of each node, you can render the lines connected them to their neighbours. In flash, I made a simple linear connection to each adjacent node, but you can go fancy if you want and connect them via bezier curves to their 2nd neighbour, using the immediate neighbour as a control point.

---

## Going Fancy

As I mentioned before, you don't have to be linear with the grid lines. Splines and beziers can be very cool.

Also, if you look at the lines in Geometry Wars, you see that they alternative between thick and thin lines. This can be implemented by adding a 'thickness' property to each node, and for the lines drawn between them, choose either the higher or the lower of the two nodes' thickness values to determine the weight of the line.

Alternatively, if you wanted to go really fancy and get a comic-book style inking look, you could create an uneven line that graduates its thickness as it approaches the node.

One final thing which I did, which really lends extra impact to the gravity warp's visual effect is to alter the left/right speaker balance based on where the nodes are clustering. A simple way of doing this is to work out the average X value of the node's current position, compared with the average X value of the node's original position (which in most cases will be the centre of the screen). Whether the average is higher or lower than the original will tell you if the nodes are clustering to the left or right sides of the screen.

---
Tags: physics, geometry
---