# Question
Title: How to resize an image texture according to the size of a sprite in directx9 or slimdxDirect3d9?
I want to know that is there any way of resizing our texture to the size of a sprite in slimdx direct3d9 or directx9. That is if my image size is 1024x768 and sprite size is 500x500, how can i resize the image in slimdx to display it fully on the sprite without any cropping.

# Answer
> 2 votes
Unless the sprite image is itself part of a larger image (see "sprite sheets"), you don't need to do any resizing of the image at runtime. You can simply adjust the geometry of the quad you are rendering so that it appears the desired size, in pixels, in your final render.

How exactly you do this depends on how exactly you are setting up your rendering pipeline (in particular, the values of the vertices you are using in your vertex buffer and the way you've configured your transformation pipeline matrices), so it's not possible to give an authoritative answer with the information you've provided. That said, it's common to either arrange for your vertices to be pre-transformed (that is, already specified in the \[-1, 1\] or \[0,1\] range) and then scale them by the render target width to obtain pixel positions, or to use pixel coordinates for the geometry in the vertex buffers and transform them in a vertex shader into clip space. In the latter case you'd simply set your vertices to be a 500x500 pixel square.

So long as you do not adjust the texture coordinates -- that is, make sure they span the full \[0,1\] range of the texture -- you'll get your image scaled down.

However, it's worth noting two things:

1. Scaling a 1024x768 image on to a 500x500 render area will distort the image (because the aspect ratio does not match).
2. If you are never going to display the 1024x768 image at its native pixel resolution, there is no reason to waste the time and memory loading an image at that resolution; you should downsize the asset (before the game is even built) to the correct, desired pixel size and you will avoid this problem entirely.

All of that being said, if you really want to manipulate the bitmap at runtime, you can lock the texture, read the bits out of it, create a bitmap object, and use that to scale the image as desired. Then you can create a new texture, lock it, and copy the bits back in.

---
Tags: directx, slimdx
---


title: "Clone" a RenderTarget2D?

text:
# Question
Title: "Clone" a RenderTarget2D?
I see that some XNA resources implement ICloneable (namely the Effect class) but textures don't. I have encountered a situation where I need to make a complete copy of a RenderTarget2D texture and use it as inputs for two separate rendering effects. One effect will change the contents of the RenderTarget2D so I can't pass it to the other effect, which is why I need two copies.

Can you "clone" or deep copy a RenderTarget2D in an easy way? My current work around is that I wrote a copy function that sets a new render target, uses a simple effect to just re-draw the contents of the target to be copied to into a quad and return the new render target. But seems like a lot of work around simply to create a copy.

# Answer
> 3 votes
I guess textures don't implement `ICloneable` for a good reason: it would be too easy to accidentally cause a FPS sink. One might think, XNA stores texture resources in the managed memory pool, so when `someRt.GetData()` gets called, texture data seems to be already there for locking, which should be fast, right? Not really, since getting actual data requires the driver to flush all commands in queue, wait for GPU to process them, and then send fresh data back for reading.

Chances are, if you're going to do your thing on a per-frame basis, it will be better to just render twice. But if you want to clone a texture once in while, a simple way of deep cloning is to walk through mipmap levels and clone them one by one:

```
static RenderTarget2D CloneRenderTarget(RenderTarget2D target)
{
    var clone = new RenderTarget2D(target.GraphicsDevice, target.Width,
        target.Height, target.LevelCount > 1, target.Format,
        target.DepthStencilFormat, target.MultiSampleCount,
        target.RenderTargetUsage);

    for (int i = 0; i < target.LevelCount; i++)
    {
        double rawMipWidth = target.Width / Math.Pow(2, i);
        double rawMipHeight = target.Height / Math.Pow(2, i);

        // make sure that mipmap dimensions are always > 0.
        int mipWidth = (rawMipWidth < 1) ? 1 : (int)rawMipWidth;
        int mipHeight = (rawMipHeight < 1) ? 1 : (int)rawMipHeight;

        var mipData = new Color[mipWidth * mipHeight];
        target.GetData(i, null, mipData, 0, mipData.Length);
        clone.SetData(i, null, mipData, 0, mipData.Length);
    }

    return clone;
}

```

---
Tags: xna, textures, rendering
---


# Question
Title: create an event for every enum value (game action handeling)
I'm currently working on creating an input-action system for my game. I simply wanted an easy way to map an ingame action to a certain key.

I've managed to do so with the following method: Create a class that holds both the action and the key for the action:

```
 public static class InputManager
{
    //states
    public static KeyboardState previousKeyboardState;
    private static KeyboardState keyboardState;
    private static MouseState mouseState;

    public static MouseState previousMouseState;
    public static InputState currentInputState = InputState.Gameplay;

    //different types of input layers
    public enum InputState
    {
        Interface,
        Gameplay
    }

    public enum GAction
    {
        Confirm,
        Cancel,
        MoveLeft,
        MoveRight,
        MoveUp,
        MoveDown,
        Inspect
    }

    public enum InputButtons
    {
        W,
        S,
        A,
        D,
        Enter,
        Space
    }

    private static List<ActionMap> actionmaps;

    /// <summary>
    /// Map an action to a key, attaching conditions for the action in the progress
    /// </summary>
    /// <param name="gaction">the action enum item</param>
    /// <param name="key">key for the action</param>
    /// <param name="action">the function we want to run</param>
    /// <param name="conditionList">allowed condition states</param>

    public static void MapAction(GAction gaction, Keys key, List<InputManager.InputState> conditionList)
    {
        actionmaps[(int)gaction] = new ActionMap();
        actionmaps[(int)gaction].conditions = conditionList;
        actionmaps[(int)gaction].keyboardKeys.Add(key);
    }

    public static KeyboardState currentKeyboardState
    {
        get { return keyboardState; }
        set { keyboardState = value; }
    }

     /// <summary>
    /// Check if a key is pressed.
    /// </summary>
    public static bool IsKeyPressed(Keys key)
    {
        return currentKeyboardState.IsKeyDown(key);
    }

    public static MouseState currentMouseState
    {
        get { return mouseState; }
        set { mouseState = value; }

    }

    // / / / / / / / / / / / / /
    //   f u n c t i o n s   / /
    // / / / / / / / / / / / / /

    public static void init()
    {
        int count = Enum.GetValues( typeof( GAction ) ).Length;
        actionmaps = new List<ActionMap>(count);
        for (int i = 0; i < count; i++)
        {
            actionmaps.Add(new ActionMap());
        }

        InputManager.MapAction(InputManager.GAction.Confirm, Keys.Space, null,
                    new List<InputManager.InputState>() { InputManager.InputState.Interface});
    }

    public static void update()
    {
        previousMouseState = currentMouseState;
        previousKeyboardState = keyboardState;

        currentKeyboardState = Keyboard.GetState();
        currentMouseState = Mouse.GetState();
    }

    /// <summary>
    /// checks if action is both used and allowed to be used [conditions]
    /// </summary>
    /// <param name="action"></param>
    /// <returns></returns>
    public static bool IsActionUsedNAllowed(GAction action){

        if(IsActionPressed(action) && isActionAllowed(action)){
            return true;
        }

        return false;
    }

    public static bool isActionAllowed(GAction action){

        return CheckAllowedActionStates(actionmaps[(int)action]);
    }

    private static bool CheckAllowedActionStates(ActionMap actionmap){

         for (int i = 0; i < actionmap.conditions.Count; i++)
        {
            if (currentInputState != actionmap.conditions[i])
            {
                return false;
            }
        }

        return true;
    }

    public static bool IsActionPressed(GAction action)
    {
        return IsActionMapPressed(actionmaps[(int)action]);
    }
    private static bool IsActionMapPressed(ActionMap actionMap)
    {
        for (int i = 0; i < actionMap.keyboardKeys.Count; i++)
        {
            if (IsKeyPressed(actionMap.keyboardKeys[i]))
            {
                return true;
            }
        }

        return false;
    }

}
}

```

To map and check for an action you use the following statements:

```
 InputManager.MapAction(InputManager.GAction.MoveDown, Keys.S, ControlActor,
                    new List<InputManager.InputState>() { `InputManager.InputState.Gameplay });`

InputManager.IsActionUsedNAllowed(InputManager.GAction.MoveDown);

```

---

I'm not liking the fact that I have to use an if statement to check if any actions have been performed though. I would much rather use events. But create a delegate and event for each action seems sluggish.

Is there any way to generate an event for every field in the enum? I know I could write my own event system, but I want to avoid mixing up c#'s build in events and my own events.

# Answer
What if you passed an Action (if needed)? When the input manager detects the key is pressed it can call the given action. That action in turn can do whatever you want.

Maybe a Func will work better for you, but the basic idea is instead of having the IM throw an event, just have it call the action/func directly

Action
Func
> 2 votes

# Answer
I was working on a tool to provide event based input for XNA games and I came across this issue as well - do I have a single key pressed event which passes in the key, or 70 separate events. I wrote some code to generate all the event delegates for all the Keys and then I just stuck them in to an input manager. I never really got round to doing any stress testing... I don't know exactly what optimisation the C# compiler does, but I would like to think that if you don't use an event, it doesn't get included, but this is probably wishful thinking.

Anyway, if you are interested I used the following to generate the events:

```
for (int i = (int)Keys.A; i <= (int)Keys.Zoom; i++)
{
    string line = "public static event EventHandler " + ((Keys)i).ToString() + "KeyPressed = delegate { };";
    lines.Add(line);
}

for (int i = (int)Keys.A; i <= (int)Keys.Zoom; i++)
{
    lines.Add("case \""+((Keys)i).ToString()+"\":");
    lines.Add(((Keys)i).ToString() + "KeyPressed(null, new KeyPressedEventArgs(keyPressed));");

    lines.Add("break;");
    lines.Add("");

}

```

The output it here (https://github.com/thk123/XGT/commit/475b31ecd8262efd214e397bf7689e94da1196bd), but like I said, it is pretty monstrous.
> 1 votes

# Answer
Here is what I used for my input handling in a XNA project I was working on. Not sure if this is a good system or not, but it seemed to work for my purposes. It sort of evolved to this, so it can probably be refactored to be a bit better. I am adding some comments, but its been a while since I looked at it.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;

namespace ClientLayer
{
    public class KeyController
    {
        //delegate to represent the action that is to be preformed on key press
        public delegate void KeyAction(List<Object> args);

        //probably should have created a class to hold all this information
        private Dictionary<Keys, int> keySensitivity;//regulates how often the action is invoked
        private Dictionary<Keys, int> keyPresses;//keeps track of how many times the key has been pressed since it last invoked the action
        private Dictionary<Keys, KeyAction> keyMapping;
        private Dictionary<Keys, List<Object>> keyArgs;
        private List<Keys> ToBeEnacted;
        private Dictionary<Keys, bool> ActOnPressed;

        public KeyController()
        {
            keyMapping = new Dictionary<Keys, KeyAction>();
            keySensitivity = new Dictionary<Keys, int>();
            keyPresses = new Dictionary<Keys, int>();
            keyArgs = new Dictionary<Keys, List<object>>();
            ToBeEnacted = new List<Keys>(); //list of keys who's action should be invoked
            ActOnPressed = new Dictionary<Keys, bool>();
        }

        public void AddKeyMapping(Keys key, KeyAction action, int sensitivity, List<object> args)
        {
            keyMapping.Add(key, action);
            keySensitivity.Add(key, sensitivity);
            keyArgs.Add(key, args);
        }

        public void AddKeyMapping(Keys key, KeyAction action, List<object> args)
        {
            keyMapping.Add(key, action);
            keyArgs.Add(key, args);
            ActOnPressed.Add(key, true);
        }

        public void AddKeyMapping(Keys key, KeyAction action, List<object> args, bool actOnPressed)
        {
            keyMapping.Add(key, action);
            keyArgs.Add(key, args);
            ActOnPressed.Add(key, actOnPressed);
        }

        public void AddKeyMapping(Keys key, KeyAction action, int sensitivity)
        {
            keyMapping.Add(key, action);
            keySensitivity.Add(key, sensitivity);
            keyArgs.Add(key, new List<object>());
        }

        public void AddKeyMapping(Keys key, KeyAction action)
        {
            keyMapping.Add(key, action);
            keyArgs.Add(key, new List<object>());
            ActOnPressed.Add(key, true);
        }

        public void AddKeyMapping(Keys key, KeyAction action, bool actOnPressed)
        {
            keyMapping.Add(key, action);
            keyArgs.Add(key, new List<object>());
            ActOnPressed.Add(key, actOnPressed);
        }

        public void handleKeyPress(KeyboardState state)
        {
            Keys[] pressed = state.GetPressedKeys();
            foreach (Keys key in pressed)
            {
                if (keyMapping.ContainsKey(key))
                {
                    List<Object> args = keyArgs[key];
                    if (keySensitivity.ContainsKey(key))
                    {
                        if (keyPresses.ContainsKey(key))
                        {
                            if (keyPresses[key] <= 0)
                            {
                                keyPresses.Remove(key);
                                keyMapping[key](args);
                            }
                            else
                            {
                                keyPresses[key] -= 1;
                            }
                        }
                        else
                        {
                            keyPresses[key] = keySensitivity[key];
                            keyMapping[key](args);
                        }
                    }
                    else
                    {
                        if (ActOnPressed.ContainsKey(key) && ActOnPressed[key])
                        {
                            keyMapping[key](args);
                        }
                        else
                        {
                            if (!ToBeEnacted.Contains(key))
                            {
                                ToBeEnacted.Add(key);
                            }
                        }
                    }
                }
            }

            for (int x = ToBeEnacted.Count - 1; x >= 0; x--)
            {
                Keys key = ToBeEnacted[x];
                if (!pressed.Contains(key))
                {
                    List<Object> args = keyArgs[key];
                    keyMapping[key](args);
                    ToBeEnacted.RemoveAt(x);
                }
            }

            IEnumerable<KeyValuePair<Keys, int>> tbr = keyPresses.Where(x => !pressed.Contains(x.Key));
            List<KeyValuePair<Keys, int>> tbrList = tbr.ToList();
            foreach (KeyValuePair<Keys, int> pair in tbrList)
            {
                keyPresses.Remove(pair.Key);
            }
        }
    }
}

```
> 0 votes

---
Tags: xna, c#, events
---


# Question
Title: Unusual Lighting Effects - Random Polygons Coloured
I am working on creating an object loader for use with iOS, I have managed to load the vertices, normals and face data from and OBJ file, and then place this data into arrays for reconstructing the object. But I have come across an issue with the lighting, at the bottom is a video from the simulation of my program - this is with the lighting in the following position:

```
CGFloat position[] = { 0.0f, -1.0f, 0.0f, 0.0f };
glLightfv(GL_LIGHT0, GL_POSITION, position);

```

This is specified in both the render method each frame and the setup view method which is called once at setup.

Various other lighting details are here, these are called once during setup:

```
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
CGFloat ambientLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
CGFloat diffuseLight[] = { 1.0f, 0.0f, 0.0, 1.0f };
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
CGFloat position[] = { 0.0f, -1.0f, 0.0f, 0.0f };
glLightfv(GL_LIGHT0, GL_POSITION, position);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);

```

The video of the issue can be found here:

http://youtu.be/dXm4wqzvO5c

Thanks,

Paul

\[EDIT\]

Normals are also supplied by the following code, they are currently in a large normals array or XYZ XYZ XYZ etc...

```
// FACE SHADING
glColorPointer(4, GL_FLOAT, 0, colors);
glEnableClientState(GL_COLOR_ARRAY);
glNormalPointer(GL_FLOAT, 3, normals);
glEnableClientState(GL_NORMAL_ARRAY);
glDrawArrays(GL_TRIANGLES, 0, 3*numOfFaces);
glDisableClientState(GL_COLOR_ARRAY);

```

\[ANSWERED!\]

I have solved the issue but can't post the answer as I have too little reputation, but it was simply down to a typo!

```
glNormalPointer(GL_FLOAT, 3, normals);

```

should read

```
glNormalPointer(GL_FLOAT, 0, normals);

```

as all the normal data is in a single un shared array, so it does not need to skip values..

# Answer
I have solved the issue, was simply down to a typo of sorts!

```
glNormalPointer(GL_FLOAT, 3, normals);

```

should read

```
glNormalPointer(GL_FLOAT, 0, normals);

```

as all the normal data is in a single un shared array, so it does not need to skip values.. I thought the three was for there are 3 values for each normal stupidly!
> 0 votes

---
Tags: opengl, opengl-es, objective-c, lighting, normals
---


title: How to rotate blocks in tetris

text:
# Question
Title: How to rotate blocks in tetris
I have a gameboard grid which is 20 rows high and 10 columns wide with the origin (0,0) being in the top left hand corner. I have a tetrimino in play, which is composed of four blocks. I have the x,y location of each block relative to the top left hand corner origin. I also have the position of the pivot, the point around which I wish to rotate which is relative to the top left hand corner origin.

Each block has an integer position in a gameboard square and thus the pivot has a fractional position inbetween blocks e.g (10.5,10.5)

My question is: Which formula can I use to rotate each block around the pivot?

I have already looked at existing similar questions and answers but could not find an answer that I could get to work.

Help would be much appreciated.

# Answer
The standard Tetris rotation logic is called Super Rotation System. SRS is suited to high-level Tetris play, allowing for many variations on wall kicks and t-spins.

> All tetrominoes exist inside a bounding square and rotate about the center of this square unless obstructed. Tetrominoes of width 3 (J, L, S, T, Z) are placed in the top two rows of the bounding square and (for J, L, and T) with the flat side down. I is placed in the top middle row.
>
> All tetrominoes spawn in 2 usually hidden rows at the top of the playfield. They are placed in the center of these rows, rounding to the left. Once a tetromino lands, it does not lock until the lock delay expires. The lock delay behavior, called Infinity by the Tetris Company, resets the lock delay whenever the tetromino is moved or rotated. Hard drop is generally mapped to up, which has no lock delay.

There is another common variant called ARS, which was used in Arika's *Tetris: The Grand Master* games.
> 27 votes

# Answer
General formula for rotating around origin is

```
xNew = x * cos(a) - y * sin(a)
yNew = x * sin(a) + y * cos(a)

```

For 90 degrees it becomes

```
xNew = -y
yNew = x

```

So, firstly get brick center coordinates relatively to pivot point:

```
x = xBrickCenter - xPivot
y = yBrickCenter - yPivot

```

Then rotate them around pivot point:

```
x1 = -y = yPivot - yBrickCenter
y1 = x = xBrickCenter - xPivot

```

And then add pivot coordinates to rotated point:

```
newXBrickCenter = xPivot + x1 = xPivot + yPivot - yBrickCenter
newYBrickCenter = yPivot + y1 = yPivot - xPivot + xBrickCenter

```

But if you need to rotate by multiples of 90 degrees, you can store four sets of brick positions for each orientation and switch between them instead of actually rotating.
> 11 votes

# Answer
You could rotate all square rings (a-through-h by 2 positions, A-through-P by 4 positions, and so on) around that pivot block:

```
ABCDE    MNOPA
PabcF    LghaB
Oh.dG -> Kf.bC
NgfeH    JedcD
MLKJI    IHGFE

```
> 0 votes

# Answer
Follow the standard 2D rotation formulas in Mathematics should do your trick.

http://en.wikipedia.org/wiki/Rotation\_(mathematics)#Matrix\_algebra
> -2 votes

---
Tags: c++, rotation
---


# Question
Title: Recommended 2D Game Engine for prototyping
**What high-level game engine would you recommend to develop a 2D game prototype on windows? (or mac/linux if you wish)**

The kind of things I mean by "high-level" includes (but is definitely not limited to):

* not having to manage low-level stuff like screen buffers, graphics contexts
* having an API to draw geometric shapes
* well, I was going to omit it but I guess being based on an actual "high-level" language is a plus (automatic resource management and the existence a reasonable set of data structures in the standard library come to mind).

It seems to me that Flash is the proverbial elephant in the room for this query but I'd very much like to see different answers based on all kinds of languages or SDKs.

# Answer
I've used pygame extensively, and it has lots of positives:

* it's a library for Python, which is a high-level language
* it's got good clear documentation
* it's got an active community

Pygame is a wrapper around SDL, a cross-platform 2D graphics library. Pygame also has wrappers for sound, music etc. Note that despite Python being a high-level programming language, pygame is (for the most part) a fairly low-level graphics library.
> 31 votes

# Answer
If you want to look at other things. You can check out Löve (which uses Lua)
> 35 votes

# Answer
I find XNA to be a very nice language to prototype in. It is easy to throw together quick ideas to see how the game play/mechanics would work, and strong enough to really get the job done. It also has a great community at the forums for help, and several 3rd party tools (physics engines/helper libraries/etc..)
> 20 votes

# Answer
**GameMaker** looks like a good introductory game-prototyping or building tool. It is based on drag-and-drop "without the need to write a single line of code", so looks to be aimed at beginners. (I've never used it, just happened across it - but their website certainly looks slick. :)
> 18 votes

# Answer
Angel (C++) and AngelXNA (C#) are worth looking at.
> 17 votes

# Answer
Adam Atomic's Flixel is also worth mentioning. A simple, modern, bare-bones game engine written in Flash. You can learn it in minutes, not days. And using Flash (or Processing/Java) keeps you from one of the most dangerous pitfalls of prototyping: You can't use the prototype's code on any serious platform. It's the game you want to prototype, not the code.
> 14 votes

# Answer
It's not specifically a game engine, but look into Processing. Some of the good points are:

* Minimal setup required. You can have something onscreen in 30 seconds.
* Can dip into Java any time for stuff like collections, but a lot of the drawing, animation and interaction syntax is much less verbose than straight Java.
* Anything you write will be compatible with Processing.js, so you can work with it anywhere you have a modern browser.
> 8 votes

# Answer
I use Novashell.

I used Game Maker as main tool, but I had a issue with YoYo Games (I will not explain here now), then I found Novashell.

Novashell is REALLY a prototyping tool, it was made by the person that also made "LORD" (Legend of Red Dragon) and "Dink Smallwood" so he could make games fast for Ludumdare (a 48h gamejam competition), it has a map editor, supports LUA scripting, is made in C++, has zlib license (meaning that you can do whatever you want with the source, short of claiming that you invented stuff that you did not), and has a physics engine (Box2D), particle system (Linear Particle for ClanLIB), supports MikMod and Fmod, works in Linux, Mac and Windows, is dead easy to use, and you can ask stuff to Seth!

EDIT: Seth is the name of the programmer (that also made LORD)
> 8 votes

# Answer
Game Maker is very cool, it basically does everything you've described. It has drag and drop icons for beginners and code for advanced users. However, after having used C++ exclusively for over a year, going back to Game Maker was... painful.

Downsides:

* No user defined data structures (nothing like C structs or C++ classes, just "objects")
* Dynamically typed (type "varAwesome = 0" and oh my god it just appeared)
* YoYo Games is evil

Upsides:

* Easy to use, hard to master
* Does a lot of low level stuff for you
* Vibrant and active community

I started making games using Game Maker in 2002. :)
> 7 votes

# Answer
I've been using DarkBASIC Professional for 2 years and really enjoy it. If you can't afford to buy the full version, you can simple download the free ad supported version. The Game Creators, makers of DBPro, also release a regular newsletter which makes pretty good reading, plus they've got a fairly large active community; all of the above can be found here:

https://www.thegamecreators.com/

Check it out, hopefully you might find something there.

Cheers, BFM
> 5 votes

# Answer
cocos2d which uses pyglet. I use these two Python libraries extensively for prototyping.

Much easier to work with than pygame.

I'm surprised it hasn't been mentioned yet!
> 5 votes

# Answer
I'd recommend Scirra Construct for beginners and quick prototyping.

The game engine itself is abstracted, so you can focus on your game entirely. Plugins enable additional functionality, the "code" is made of draggable event, condition and action blocks etc.

Construct is under active development and has an active community as well.
> 5 votes

# Answer
The Slick Framework written in Java is a good choice. It's what I first used to learn to program. The benefits are it runs cross platform, can produce applets for the web, and has fantastic tool/library support through Eclipse or whatever else the Java environment has. That said I eventually switched to Flash simply because if you want to distribute your games there's nothing easier or more effective.
> 3 votes

# Answer
The Scrolling Game Development Kit version 2 is the second major iteration (rewrite) of a game development IDE and framework for exactly this kind of prototyping and simple 2-D game development. As the second iteration, it takes advantage of modern languages (C#) and technologies (reflection on custom code) as well as working out some of the fundamental flaws in the design (now it allows you to place sprites directly in the map editor rather than only a path which must be externally connected to a sprite, and it doesn't try to be quite such a Wysywig editor because there are some things you want to happen at run time only and others you want at design time only).

Some of the features of interest:

1. The vast majority of the framework code is exposed and editable within the IDE. If you don't like the way the "PushTowardSprite" built-in function behaves, you can bring up the editor and change it, or add your own that will appear in the list right along with all the built-in commands.
2. You mentioned the ability to draw polygons. This framework is based on OpenTK, which is a .NET wrapper around OpenGL. So you have all the power of OpenGL at your fingertips. There's a single class "Display.cs" in the framework code that you can edit within the IDE do add whatever drawing features you want.
3. Much of the framework is targeted as side-scroller physics (walking on slopes, riding platforms, etc), so a lot of that code is already done for you; of course you can customize or ignore it for other 2-D game types. A Tetris game has been written with it.
4. Parallax scrolling
5. Alpha translucency can be embedded in the graphics or applied to the drawing of any graphic.
6. All project data is saved in a single XML file (a .NET dataset). External editors can access the file thereby extending the features available in the IDE if necessary.
7. Projects are compiled first to C# projects (compatible with Visual Studio) and then to EXE files (with all the resources embedded). If necessary, you can load the project into Visual Studio for enhanced debugging or code development interface.
> 3 votes

# Answer
With PreviewLabs, a company specialized in rapid prototyping, we're often using Unity3D to prototype 2D Games.

Although it's a 3D engine, there are several ways to use it for 2D prototyping. These are the main advantages:

* It's free to use for the PC and Mac platforms
* The paid versions also work for iOS and Android, allowing you to see how your concept would work on a different platform.
* It comes with a physics engine, which you can also use when prototyping 2D games.

I'm writing a series of blog posts on how Unity3D can be used for 2D game prototyping; this is the first one: Prototyping 2D Games in Unity3D
> 3 votes

# Answer
I started using FlashPunk for my first game development project, and so far it has been really slick. It is a Flash library built for game design. It is a bare-bones game engine similar to Flixel, but is more like GameMaker, being more user-friendly to beginners than Flixel. FlashPunk along with the Ogmo Editor make it very efficient to get right to level design without having to spend a lot of time on coding. More info about all three of these can be found at the Flash Game Dojo.
> 2 votes

# Answer
I'll second the mention of Game Maker. I would say, if every game engine falls on a continuum from "easy to use/learn but limited in what you can do" to "really powerful, but takes a long time to master"... Game Maker is pretty much the definition of the easy-to-use extreme. As Cyclops says, most basic functionality (sprites, creating game objects, movement, collision detection, scorekeeping, etc.) are drag-and-drop icons. It actually does include a fairly robust scripting language you can use too, once you start getting good... but when you start writing your entire game in their embedded scripting language, maybe it's time to "graduate" to a scripting language like Flash or PyGame.

Still, I've had great success with Game Maker as a beginner, no-programming-needed tool for game design students, and can't recommend it enough.
> 1 votes

# Answer
I'm a very beginner in game making, and I was impressed to manage to make something out of pygame so quickly and easily. Python + SDL = easiness assured.
> 1 votes

# Answer
Well, if it's for prototyping you don't really need a slick back-end with resource management and stuff like that. As long as you can load graphics and display them you're mostly set. I'm going against the grain and propose 'write your own'. You will lose zero time figuring out how to use someone's api. If write-your-own is really not an option, DirectX comes with a sample framework that provides most basic services. Not being bound by a framework means not losing any time following its rules, and not being limited by its scope. I've been prototyping as a job, and my fastest results were when I could just bash in code without having to worry about, or being hampered by, a framework. A 2D wrapper really needs no more than loading images and being able to display them at x,y - possibly with scale, rotation and if you want to be trippy, shader. The rest you can code as you need. For a prototype that is - the code won't be nice.
> 1 votes

# Answer
Torque-2d by GarageGames is a great game engine with a great community, some really impressive add-ons, and built-in support for Windows, Mac, and Wii, and even the iOS (on separate license). It costs $99.

Unity3d (you can develop 2d games on it) is another very good high quality game engine with a relatively low barrier to entry. Again, great community, and really cool multi-platform support, including iOS and Android, in addition to Win/Mac, Wii, Xbox, Playstation, and the web.

A great iPhone centric game engine is cocos2d for iOS.
> 1 votes

# Answer
Your question is about what it takes to write a 2D game prototype, but I think there's something else to consider: the biggest advantage of Flash is what it takes to share that prototype with others. Almost everyone already has Flash installed. I can upload a SWF and pass the URL to someone over chat or email. No download, no install, no unzip, no exe, no cross platform issue. I ended up picking Flash because it was so easy to share and get feedback. Iteration involves uploading again and telling them to reload, and I wanted quick iteration for prototyping. (Javascript + Canvas/SVG is another useful option, and I'm sure we'll soon see libraries like Flixel/Flashpunk for JS).
> 1 votes

# Answer
PixieEngine is a web based IDE and game development environment. It uses CoffeeScript for scripting and provides a built in editors for pixel art and sound effects.
> 1 votes

# Answer
HGE Seems Great.It have Particle Editor,GUI Editor,And used by pro programmers.
> 1 votes

# Answer
**There is always GLBasic.**

It's a fairly high level language and has recently been expanding its mobile support.

* It's both 2D and 3D
* Free for non commercial
* Basic sprite commands, with pixel or block collision
* Write once and deploy to many devices and platforms (mostly)
* Has Box2D support via wrapper (search forums)
* Custom data TYPES with functions (close to a class but missing much OOP functionality)
* Can get a sprite moving on the screen in a short time with few lines of code
> 1 votes

# Answer
I've been on a similar quest and ran across a few other tools not mentioned here:

* Stencylworks is a IDE / dev environment for building Flash games very quickly and easily, visual interface for existing modules. it seems to be 100% free, not open source, and key advantages include slick, codeless coding (it's not like Gamemaker's schitzoid script/visual interface). I do worry about the limits of the visual interface - unclear how properly object-oriented it really is; it certainly has simple stuff; presumably javascript script editor's in there somewhere, but haven't seen it yet. It seems to be meant for collaborative development at its core (chat builtin to IDE; all resources and behaviors hosted on a server, user-contributed). That could be GREAT for prototype development. I haven't doen much with it yet but the tutorial was dead simple, and there's no sign of any timeline (which is why normal Flash is so bad for games - timeline metaphor is sooo wrong for games)

I've tried a few other weirder ones too.

Alice is a 3D game / dev environment which is open source - looks kind of clunky.

Kodu, going beyond Gamemaker on the easy/limited spectrum, aimed at kids, lets you build games with an Xbox controller. free from Microsoft Research

Scratch, from MIT Labs, is free and really basic 2D, aimed at getting kids into coding. Visually clunky. Flexible though.

Going waaaay back to Papert's LOGO, Microworlds JR lets you write in logo, allegedly. Needs an update to be useful, IMO.

For me, so far, it's coming down to Construct 2 vs Stencylworks...though I'll check out how easy it is to build a decent 2D game in Unity, as I know and like Unity.
> 1 votes

# Answer
FlatredBall It's free (not open source) 2.5D (2d with 3d primitives) game engine for XNA and Silverlight. More in features.
> 0 votes

---
Tags: 2d, prototyping
---


# Question
Title: Implementing recoil in a realistic and balanced way?
To clarify, I've seen this post already

I really like the idea that the chosen answer suggests, yet when I go to implement it the recoil still doesn't "feel" right. The problem is mainly the fact that I'm moving the crosshair instantly to a new location and it feels quite jerky when playing around with it. I think that in order to properly implement recoil I need to move the crosshair more than once over multiple game ticks.

I think the main issue is that many games with realistic recoil "auto re-aim" (if you will) the gun as part of the recoil algorithm. This is from my experiences with various Source Engine games like Garry's Mod and Counter Strike. My best way of describing what I see and thinking about how it is implemented is that a point is chosen with a variance (usually up and slightly right) from the fire coordinates. The gun follows a sort of parabolic path (height depending on velocity of recoil) and eventually gets to the new point.

I'm getting kind of long winded but I hope most of what I said makes sense. Should I attempt to model the recoil implementation in the Source Engine? How would you go about implementing a realistic recoil algorithm? Are there any open source fps game engines that may be able to provide some inspiration?

# Answer
Just thinking off the top of my head, but a spring model might work well here. You can think of the recoil jolt as being a sort of "particle" in 2D that has a position and velocity, and is attached to the origin by a spring. When the gun is fired you'd give the particle an impulse (i.e. an instantaneous velocity change) up and to the right, then simulate its physics; it would initially move in the direction of the impulse, but the spring would pull it back to the origin. You'll want the spring to have a good deal of damping so that it doesn't oscillate. You can read about simulating a spring online; there are lots of articles about it.
> 5 votes

# Answer
*First*, I would recommend stepping away from your computer for a bit. Finding the closest firing range and going there and renting a handgun and actually squeezing off a few rounds to see what it actually feels like.

Even if you have gone shooting before, I would recommend going again, but this time take it from the perspective of an scientist rather than a shooter. Ask the guys there if you can bring in a video camera, and if they are okay with it then set the tripod up right over your right shoulder and pointed down range. Try firing at different speeds, keep your target sheets and mark test cases. When you are all done go back and review the footage of your shots and compare that to your results. I think if you do that you will glean a much better perspective of how this stuff should work.

Second, I would say there are really a couple core attributes involved

* **Kick Strength**: The vector kick is actually straight backward from the barrel, not up or in any other direction. The reason a shooters aim drifts up is because you are holding the handle mounted beneath barrel, your arm becomes like lever; your body tries to stay still while the gun tries to move back. As the energy from firing the bullet is diffused into your body, your elbow and shoulder retract and your muscles flex to offset the energy.
* **Player Strength**: This works to offset the kick. The stronger you are the less the kick causes your aim to drift. If you were to weld a handgun to the side of a battleship and fire it, its kick would effectively be offset by the mass of the ship. So player strength is inversely related to kick strength.

Another thing to point out is one vs two handed weapons. While a shotgun or rifle might have a much higer kick than say a medium calibur handgun. Because its stabalized with two hands, your effective strength is much higher. This should be taken in to account. Try (*don't try actually*) shooting a shotgun single handed and you'll see what I mean.
* **Player Aim**: This represents the players ability to hit something they are aiming at. It represented by two components, *speed* and *accuracy*. This is manifested in games as the widening reticle widening while moving and the slowly settling when slowed or stopped, but its applicable to post recoil as well.

But there is another component here that is at play, *muscle memory aiming*. After you fire, you need to re-aim at your target. But you can usually do it a lot faster than it initially took you to aim because of muscle memory. Using your short-term muscle memory you can reset your aim close, but not perfect, to your intended target. Then from that position you correct your aim over time to get back to your maximum potential to aim.

This is one of those cases when it helps to go to range. If you focus on your gun sights you will be suprised how much your gun is actually waving around, even when trying to hold it still.

Using these properties, the pseudo-algorthm I would make for gun recoil would look something like this:

* Use `kick_strength - player_strength` to determine `kick_magnitude`
* apply `kick_magnitude` to a random up-ish unit vector as `kick_aim_position`. \[To simulate your body diffusing `kick_strength`\]
* Take `initial_aim_position` and use `muscle_memory_accuracy` to determine distance and pick a new point that distance away from your aim as `muscle_memory_aim_position`. \[To simulate re-aiming using muscle memory only.\]
* Lastly settle slowly back to your `inital_aim_position`. \[To simulate correcting your muscle memory with visual input, aiming back at what you want to hit\]
> 4 votes

# Answer
The spring model will result in an unrealistic effect. since when a shooter wants to tune his gun after a shot, he slow his movement when he gets near to original target. I'm not sure how my algorithm will turn out but I think it will generate good result:

lets say a player originally targeted point x,y; when he shots, I'll set random values to two new parameters dx,dy; I'll then adjust shooters target to x+dx/(1+time\*const\_value), y+dy/(1+time\*const\_value). note that time is calculated from when player shot a bullet.const\_value is something based on weapon type. for example for snipe rifle it's something smaller than 1, but for a shotgun it's larger than 1. random value for dx and dy is also based on weapon type, for a snipe it's something small but for shotgun they are big.
> 0 votes

---
Tags: algorithm, first-person-shooter
---


title: How to get started in Card Games

text:
# Question
Title: How to get started in Card Games
My end goal is to play a card game with my friends from other locations over the internet. I am going to start with a card game like blackjack and want people to be able to play in real time or close to it. I am not really sure where to start here and in which language. I was kind of thinking of making a website that can do this but I am not really sure. My end goal is to play MTG with friends and build decks.

Any ideas on a language to choose or where to get started? My current plan is C# asp.net webforms... Would Java be a good idea? I dont need it fancy, just functional. I am good at C and C# and some Java.

Thanks.

# Answer
> 2 votes
Given your requirements, I'd suggest ASP or PHP for your game logic, a SQL database for your cards and so on, and DHTML/Ajax to breathe some life into the interface. This approach will be clean, stylish and responsive if implemented well. HTTP provides the reliable communication you need. Because card games are turn-based, the page-refresh paradigm can work very well even without DHTML, eg. MArcomage.

If you want 3D (cards), you could pull in WebGL to do that work for you.

Remember that if you want the game to be ostensibly secure from cheating, you need to implement the logic in backend, so don't use JS for your core game logic, only for the presentation. Clients cannot be trusted in regards to game state updates, only the server can. Clients should only send state delta's to the server, for it's intelligent approval and subsequent incorporation into the actual current game state.

The benefits of the ASP-or-PHP/HTML/CSS/JS approach over any compiled language, including something like Flash, is that the code-debug cycle is quicker -- "recompile" is a page refresh away.

On the other hand, if you're particularly familiar with doing all the necessaries in, say, Java, then by all means. But I guess if that were the case, you wouldn't be posting here ;)

# Answer
> 1 votes
It really depends on what languages you already know. but if I were to write a server I suggest you go with either asp.net or node.js.

---
Tags: c#
---


title: AABB for a tile based world

text:
# Question
Title: AABB for a tile based world
I'm on my way with a tiled based game. I have correctly implemented scrolling, position handling etc.

I have (before) had a simple collision system that is a really bad one, and now I'm going to switch from simple x and y checks to AABB.

The real problem isn't really about AABB itself, since I've made a simple application demonstrating the technique - it works like intended. This is for singular, independent objects that is static.

Since I know the technique and how to resolve collisions correctly I wanna apply this AABB technique to my tile world. It is now the real problem (or question?) arises.

*Since the world is built on tiles and the world's objects is built together to a world, how would I implement the AABB? Before it was only for single static objects, now for a whole world. Is it possible to create a single world static object or are there any better idea out there?*

Should I create a single box for every single tile in the world? It doesn't sound well, but how **should I fight this problem down**?

Any help is appreciated!

**Comments to Nick's answer**:

> Considering what you've said about how you previously had a "simple collision system that was a really bad one", I assume you want the latter.

That's correct. The previous collision system made my character get stuck in tiles and it wasn't working properly.

> So you can see how it will haphazardly overlay your four tiles. Your AABB for the object then is a rect with x=7, y=10, w=12, h=15. Let's say this is your only obstacle in the world.

I understand, I think. Does this necessarily mean I have to create a single AABB for every tile?

> You can see that due to his width and height, he now overlaps the top left of your obstacle at {7,10}. So resolve the collision. That's all there is to it.

Yep, that part I understand. For now, the world is built from a single 2D array, but is it really efficient to create an AABB for every obstacle?

Oh, I think it does not really matter if I only loop through the obstacles and tiles in the area where the player is..

# Answer
> 2 votes
I think you're misunderstanding the nature of collision detection using AABBs, as a whole, thereby confounding your question.

Tile-based collision: Use if you're only ever going to have obstacles that cover complete tiles, never just parts of tiles. This typically restricts your character to moving jerkily from tile to tile, also.

AABB-based collision: Use if you want obstacles (and characters) that can partly cover tiles, for example, stand your character on the border between tile {0,0} and {1,0}. Now he's covering part of each. This also allows "free movement" for mobile entities.

Considering what you've said about how you previously had a "simple collision system that was a really bad one", I assume you want the latter.

AABB collision detection is simple. You have N objects in your world. Because you must check every object against every other object, you have the following funadmental code:

```
for each entitiy in entityList
   for each otherEntity in entityList
       if entity != otherEntity
           if (entity.overlaps(otherEntity))
               resolveCollision(entity, otherEntity)

//resolveCollision applies new vector forces to cause objects to bounce off one another, or stop dead, or some such.

```

In your empty world, begin placing obstacles. These need not fit your ground tiles exactly. That is, an obstacle like a fallen tree may completely cover some ground tiles, while it may only partially cover others. When you place the object, calculate your AABB. Let's say your 10x10 pixel tiles are placed at {0,0}, {0,10}, {10, 0} and {10,10}, so you have a small square of four tiles. You don't need to place your obstacle at any of these points, you could instead place it at {5,5}. If it has a width of {7,10} then it would run to {12,15}. So you can see how it will haphazardly overlay your four tiles. Your AABB for the object then is a rect with x=7, y=10, w=12, h=15. Let's say this is your only obstacle in the world.

Now put your player character in the world. He starts moving. Every update, potential collisions must be check for. At some point, your player walks down and right. His AABB is w=3, h=3, and he is now standing at 6, 9. You can see that due to his width and height, he now overlaps the top left of your obstacle at {7,10}. So resolve the collision. That's all there is to it.

Using AABBs, you can now use floating point values for your positions, allowing finer control, whereas with a tile-collision approach, you have a quantised space (a 2D array) that restricts positioning to only the exact indices into that array.

---
Tags: tiles, aabb
---


# Question
Title: How would one determine the length of a path?
I have a game that requires each player to move along one specified path. I draw the path using Bézier curves. How can I determine the total *real* (not linear) length of the path and the distance that each player had made? (The distance between the start point and a specified point on the path.)

UPDATE:

The path is represented in a Cartesian plane (2D).

# Answer
> 7 votes
As the previous answers said, computing the length of a Bezier curve it's hard (impossible?). I would say that 100% of the games use an approximation of the length, which is pretty much always accurate enough.

A few month ago I implemented it using the proposed approach of breaking the curve into "small" segments and adding their length. There's an example of a C++ implementation here.

# Answer
> 11 votes
Measuring the length of a Bezier curve is hard. If you don't mind a slight inaccuracy, a simple solution would be to approximate the Bezier curves with straight lines and calculate the sum of the line lengths. The more segments you create, the better the approximation.

# Answer
> 7 votes
Higher order (i.e. greater than 1st order) spline length parameterization has to be approximated; it cannot be represented directly, hence the fact that it's not easy to find direct solutions to this.

Some extant implementations (copy-paste code):

Using Chebyshev approximations, according to the authors, accuracy grows as curve size increases. Look at pp. 7-8 pseudocode, the rest is a description of other algorithms on which they based their approach which you can ignore. A number of references online refer to this method as a good one.

See also these concise approaches.

# Answer
> 5 votes
This started out as a comment on the comment on @bummzack's answer, but grew too long.

> how can I determine how many segments should I have

There are two approaches. The first is just the standard algorithm for rendering a Bézier curve: the control points form a bounding box of the curve, so if all of the control points are within epsilon of the line segment from start point to end point you approximate as a line; otherwise you subdivide using de Casteljau's algorithm. Epsilon is chosen according to the error you wish in the final result. (For rendering it's usually 0.5 pixels).

The other approach is a refinement of that using interval arithmetic. Take the length of the line from start to end as the lower bound, and the sum of the lengths of the lines through the control points as the upper bound. Again, subdivide as required by your final error requirements.

One normally subdivides at t=0.5, but de Casteljau's algorithm allows splitting at any point, so if you have a cubic Bézier with control points C\_0 to C\_3 and C\_2 is much nearer the line segment between the endpoints than C\_1 you might find that splitting at one of 1/3 or 2/3 gives tighter bounds. I haven't worked through the algebra to justify which would be better, but you can experiment and report back if you want. If nothing else, I wanted to point out that the option is there.

# Answer
> 3 votes
Calculating the length of a parametrized curve can be done by taking the integral of sqrt((dx/dt)² + (dy/dt)²), where dx/dt is the derivative of the x-component of the curve, and dy/dt is the derivative of the y-component of the curve. In the case of a Bézier-spline, these two are the same, as the equation can be extended to any dimension.

The formula for a cubic Bézier-spline is the following one: B(t) = (1 - t³) * P0 + 3(1 - t)²t * P1 + 3(1 - t)t² * P2 + t³ P3 where P0 through P3 are the control points.

According to Wolfram|Alpha, the derivative of this formula is: d(B(t))/dt = 3(t(t(P3 - P0) + P2(2 - 3t) + P1(3t² - 4t + 1))

Now you can put this back into the equation for the length of a curve, and calculate the integral from t = 0 to t = 1. Unfortunately, Wolfram|Alpha times out when I try to do this. You can do numerical integration, however.

---
Tags: algorithm, geometry, splines
---


# Question
Title: Stuck on development of turn-based-strategy game
I am developing a turn based political/military strategy game similar to the DOS game Conflict. I have my game design document completed, but I'm having trouble actually putting together the logic of the turns.

How do I determine the strengths/weakness of the various nation-states in my game? Is there a common set of mathematical formulas somewhere on the interwebs that I can modify? Or do I need to come up with my own?

If I do need to come up with my own, how do I go about doing this? I have very limited experience playing games like Dungeons and Dragons and Settlers of Catan--would it be a good idea for me to buy a copy of a board game that is similar to my idea and model my game off that?

# Answer
> 4 votes
There's no easy answer, without your knowing what sort of strengths and weaknesses *you* actually want... And I'm guessing this is part of the problem.

You really don't need any fancy formulas (yet?). Start with simple arithmetic and take it from there. It's actually those very numbers that give your game a unique feel in terms of how it plays.

Before you go off and buy anything, think a bit more about the terms in which you want to differentiate the sides. This could be anything from resource gain to combat strength for all or particular units. It could be a special ability such as being able to have an additional turn before the enemy. It could be just about anything. Card games like MTG are a great example of things you can tweak to make play different from player to player.

If you start randomly tweaking some of your fundamental values in your game mechanic, according to which nation is being played, you'll start seeing imbalances quickly enough, and then you will start seeing opportunities juxtaposed.

---
Tags: game-design, logic, methodology, balance, turn-based-strategy
---


# Question
Title: How to check Early Z efficiency on AMD GPU with Windows 7
I have a game using DirectX 9, and a development station using Win 7 x64. I am still able to get access to another station with Vista x64 / dual booted with WinXP x86.

I wanted to check early Z efficiency in the game and to my sadness all tools I have tried seem to be unable to perform this task:

### AMD PerfStudio

* AMD GPUPerfStudio 2 does not support DirectX 9 at all
* AMD GPUPerfStudio 1.2 does not install correctly on Windows 7. When I have tweaked the MSI package (a simple OS version check adjustment was needed), it complained the drivers I have do not provide needed instrumentation. The drivers old enough to support the GPUPerfStudio would most likely not be able to operate with my Radeon 5750 card (though this is something I am not 100 % sure, I did not attempt to try any older drivers, not knowing which I should look for)

### PIX

PIX does not seem to contain any counters like this. It offers some ATI specific counters, but when I try to activate them, the PIX reports "PIX encountered a problem while attaching to the target program."

---

I do not want to upgrade to DX 10/11 just to be able to profile the game, but it seems without the step I am somewhat locked with a toolset which is no longer supported.

I see only one obvious options which would probably work, and that is using WinXP (or with a little bit of luck even Vista) station, perhaps with some older AMD card, to make sure GPUPerfStudio 1.2 works.

Other than that, can anyone recommend other options how to check GPU HW counters (HiZ / EarlyZ in particular, but if others would be enabled as well, it would be a nice bonus) for a DirectX 9 game on Windows 7, preferably on AMD GPU? (If that is not possible, I would definitely prefer switching GPU to switching the OS, but before I do so I would like to know if I will not hit the same problem with nVidia again)

# Answer
Early Z is just a comparison of depths and ditching off the pixel shader. Why don't you compare overall performance with Early Z enabled and then with it disabled (via modifying the depth of your pixel in the pixel shader by a really insignificant value) ?
> 2 votes

# Answer
Based on the feature list it seems even nvPerfHUD no longer supports DirectX 9 on Win7, but it is still supported on Vista. This is kind of surprise to me, I though the drivers for Vista / Win7 are almost identical, it would be interesting to know the reason. There is however one post on nVidia forum which mentions "Windows 7 x64, NVIDIA GeForce 8600 GTS 512MB, Drivers 266.58 & NVPerfHUD 6.7" as a working configuration, therefore this might be just a feature list oversight:

> * Supports DirectX10 on Windows Vista or Windows 7
> * Supports DirectX 9 on Windows XP and Windows Vista

The new nVidia debugging product nSight does not support DirectX 9 at all.

Unless the nvPerfHUD still works with Win7 and DX 9 (can anyone confirm?), it means the options for DirectX 9 profiling seem to be quite limited:

* use Vista (or WinXP, with nvPerfHUD upto 6.62) machine with recent nVidia card and nvPerfHUD
* use Vista (or WinXP) machine with old ATI card and GPUPerfStudio 1.2
> 1 votes

---
Tags: windows, directx9, gpu, profiling
---


# Question
Title: COLLADA: Inverse bind pose in the wrong space?
(Crosspost from StackOverflow)

I'm working on writing my own COLLADA importer. I've gotten pretty far, loading meshes and materials and such. But I've hit a snag on animation, specifically: joint rotations.

The formula I'm using for skinning my meshes is straight-forward:

```
weighted;
for (i = 0; i < joint_influences; i++)
{
    weighted +=
        joint[joint_index[i]]->parent->local_matrix *
        joint[joint_index[i]]->local_matrix *
        skin->inverse_bind_pose[joint_index[i]] *
        position *
        skin->weight[j];
}
position = weighted;

```

And as far as the literature is concerned, this is the correct formula. Now, COLLADA specifies two types of rotations for the joints: local and global. You have to concatenate the rotations together to get the local transformation for the joint.

What the COLLADA documentation does not differentiate between is the joint's local rotation and the joint's global rotation. But in most of the models I've seen, rotations can have an id of either `rotate` (global) or `jointOrient` (local).

When I disregard the global rotations and only use the local ones, I get the bind pose for the model. But when I add the global rotations to the joint's local transformation, strange things start to happen.

This is without using global rotations:

And this is with global rotations:

In both screenshots I'm drawing the skeleton using lines, but in the first it's invisible because the joints are inside the mesh. In the second screenshot the vertices are all over the place!

For comparison, this is what the second screenshot *should* look like:

It's hard to see, but you can see that the joints are in the correct position in the second screenshot.

But now the weird thing. If I disregard the inverse bind pose as specified by COLLADA and instead take the inverse of the joint's parent local transform times the joint's local transform, I get the following:

In this screenshot I'm drawing a line from each vertex to the joints that have influence. The fact that I get the bind pose is not so strange, because the formula now becomes:

```
world_matrix * inverse_world_matrix * position * weight

```

But it leads me to suspect that COLLADA's inverse bind pose is in the wrong space.

So my question is: in what space does COLLADA specifies its inverse bind pose? And how can I transform the inverse bind pose to the space I need?

# Answer
I started by comparing my values to the ones I read from Assimp (an open source model loader). Stepping through the code I looked at where they built their bind matrices and their inverse bind matrices.

Eventually I ended up in `SceneAnimator::GetBoneMatrices`, which contains the following:

```
// Bone matrices transform from mesh coordinates in bind pose to mesh coordinates in skinned pose
// Therefore the formula is offsetMatrix * currentGlobalTransform * inverseCurrentMeshTransform
for( size_t a = 0; a < mesh->mNumBones; ++a)
{
    const aiBone* bone = mesh->mBones[a];
    const aiMatrix4x4& currentGlobalTransform
        = GetGlobalTransform( mBoneNodesByName[ bone->mName.data ]);
    mTransforms[a] = globalInverseMeshTransform * currentGlobalTransform * bone->mOffsetMatrix;
}

```

`globalInverseMeshTransform` is always identity, because the mesh doesn't transform anything. `currentGlobalTransform` is the bind matrix, the joint's parent's local matrices concatenated with the joint's local matrix. And `mOffsetMatrix` is the inverse bind matrix, which comes directly from the skin.

I checked the values of these matrices to my own (oh yes I compared them in a watch window) and they were exactly the same, off by maybe 0.0001% but that's insignificant. So why does Assimp's version work and mine doesn't even though the formula is the same?

Here's what I got:

When Assimp finally uploads the matrices to the skinning shader, they do the following:

```
helper->piEffect->SetMatrixTransposeArray( "gBoneMatrix", (D3DXMATRIX*)matrices, 60);

```

Waaaaait a second. They upload them *transposed*? It couldn't be that easy. No way.

Yup.

Something else I was doing wrong: I was converting the coordinates the right system (centimeters to meters) *before* applying the skinning matrices. That results in completely distorted models, because the matrices are designed for the original coordinate system.

**FUTURE GOOGLERS**

* Read all the node transforms (rotate, translation, scale, etc.) in the order you receive them.
* Concatenate them to a joint's **local matrix**.
* Take the joint's parent and multiply it with the local matrix.
* Store that as the **bind matrix**.
* Read the skin information.
* Store the joint's **inverse bind pose matrix**.
* Store the joint **weights** for each vertex.
* Multiply the **bind matrix** with the **inverse bind pose matrix** and **transpose it**, call it the **skinning matrix**.
* Multiply the **skinning matrix** with the **position** times the joint **weight** and add it to the **weighted position**.
* Use the **weighted position** to render.

Done!
> 4 votes

---
Tags: mathematics, matrix, collada, spaces, skinning
---


# Question
Title: What's the best way to create animations when doing Android development?
I'm trying to create my first Android game and I'm currently trying to figure out (with someone that will do the drawings and another programmer) what the best way to create animation is. (Animations such as a character moving, etc.)

At first, the designer said that she could draw objects/characters and animate them with flash so she didn't have to draw every single frame of an action. The other programmer and I don't know Flash too much so I suggested extracting all the images from the Flash animation and making them appear one after the other when the animation is to start.

He said that would end up taking too much resource on the CPU and I tend to agree, but I don't really see how we're supposed to make smooth animations without it being too hard on the hardware and, if possible, not have the designer draw every single frame on Adobe Illustrator.

Can an experienced Android game developper help me balance this out so we can move on to other parts of the game as I have no idea what the best way to create animations is.

# Answer
> 12 votes
If you're considering 2D animation, rendering one sprite and then another will not be a problem for the device (unless your sprites are huge).

Below is a typical animation sprite that is the first one I found with a little searching. This is a commonly used technique and there are lots of websites that offer free (and otherwise, always check the license) spritesheets.

Image + author source: here

The green is set as the transparent colour of the image so that you don't have any unwanted areas of colour. You will need to know the coordinates of each animation in the animation sequence in the spritesheet in order to play them.

For Android, we can take a look at an open source game engine by Chris Pruett (formerly of Google) called Replica Island. The source code is available, and we can look at his SpriteAnimation.java and SpriteComponent.java.

A `SpriteAnimation` is simply created with a frame count and a unique ID and each actor in the game can have multiple animations. The `SpriteAnimation` can be given a number of `AnimationFrame`s, each with a duration in milliseconds. This means that different animations can be swapped in and out depending on if the character moves or attacks etc (see in `AnimationComponent.playAnimation(int id)`).

Each iteration of the game loop, the `AnimationFrame`'s `getFrame(float time)` is called, and it checks how much time has passed since the last main loop iteration and decides which frame to play next, then returns the frame to get sent off to the rendering system. This allows it to skip animation frames if the animation is going too slowly.

I hope this example works, and you can see it being used in the actual game on the Android Marketplace here.

---
Tags: android, animation
---


# Question
Title: How to prevent a certain textured quad from the effect of the pixel Shader at the run time in slimdxdirect3d9 or directx9?
I am having a video and and image slide show being rendered simultaneously. Both video and the image is being rendered by the help of texture and two different quads. Video is being rendered on the whole screen but the image of the slide show is being rendered along the video on some particular area of the screen. I am using pixel shader to give effects in my slide show but the pixel shader is affecting both the textures being rendered that is my video and the image slide show. But I want it to give effect only to the image slide show. For this I am doing Device.PixelShader=null when the video quad is being drawn but giving my pixel shader to the device when the the image is being drawn. But I want to know that is there any other way that can prevent my video quad from the effect pf the pixel shader.

# Answer
Yes, that's what you are supposed to do. When you use a shader, it stays bound yo the graphics card until you set a new one, so unselect it when you don't want it to be applied.
> 0 votes

---
Tags: directx, slimdx, video
---


# Question
Title: If "ResourceManager" classes are considered bad, what are the alternatives?
I'm hearing conflicting opinions such as:

* "Dedicated Manager classes are almost never the right engineering tool"
* "Dedicated Manager classes are (currently) the best way to survive a large project with thousands of resources"

Let's take a classic ResourceManager class that has the following functionality:

* Loads assets (textures, audio, 3D models, etc)
* Ensures assets are only loaded once by keeping a cache
* Reference counts assets to determine if they can be deallocated
* Hides where the actual assets came from (e.g., could be one file per asset, or all assets in one package file, or assets could even be loaded over the network)
* Can reload assets without restarting the program, which is extremely useful for the artists working on the game.

**Let's also take the "singletons are bad" argument off the table** by pretending these ResourceManager objects are not singletons, and instead are passed around via dependency injection.

Then there is the "use a factory" or "call it a factory" argument. My problem with this is that, yes, it is a factory, but it's also a cache and a reloader (for lack of a better word). Calling it a factory doesn't describe it properly, and if I make it a proper factory then where does the caching and reloading get implemented?

I agree that "Manager" classes are often a symptom of bad architecture, but in this particular case **how could it be restructured and still retain all of the functionality**? Is this a situation where a "Manager" class is actually appropriate?

# Answer
I think the issue is not that this is a bad design. The issue is that the name "Manager" is nondescript, like "Update" and "Process" and "Actor". It is unhelpful to someone attempting to understand this system, and it creates confusion if you ever have other classes that perform some operation on assets.

However, naming things in a way that efficiently conveys their purpose is *really, really hard*. Most systems are too complicated to be made obvious by their name. The best you can do is try to narrow down what specific idea makes this a class cohesive, and what other classes need to be obviously different, and pick a unique word that kind of fits.

IMHO, the most important feature of a good name is that it is unique within the context that people will see it (the code base), and it is easy to remember. The test should be that can you have a conversation with your teammates who are familiar with the code without having to clarify what you are referring to. This would also help if you ever need to write reference documentation.

Finally, consider that if you can't describe that cohesive idea, it may not be very cohesive. For example, you might separate the caching and referencing counting in an AssetCache, and keep the loading in an AssetLoader. But that really depends how complicated and intertwined the code is.

But if your AssetManager is cohesive enough, and nothing else in your game is AssetManagery, then it might be a perfectly good name.
> 9 votes

# Answer
"Do I do this in one place, or do I do it many?"

Loading logic is usually centralised to a single point of access because it tends to be run only at key points in the application, where we are trying to get it out of the way ASAP. This usually takes place at app startup, game level startup, or when player world position demands the loading of a new chunk to keep the experience seamless. Considering this is done as a batch process (whether in one massive chunk or many smaller ones doesn't really matter), it makes sense to have one method or set of methods to call, to kick this process off.

On most platforms, loading is asynchronous, so you actually have little choice but to keep the code flows for loading and other app logic separated, another reason for abstraction of resource management functions into their own class.

Lastly, a few of points to think on:

Resource loading is not run very often compared with eg. game logic, so is it worth adding complexity to your individual game objects to do this? Game objects are usually kept light as possible and are intended only for what is needed during simulation.

*Should* an object be responsible for it's own creation and destruction? This can cause major headaches during entity management. If you expect an object to perform it's own creation process (including getting resource dependencies) then likewise it will have the responsibility of destroying itself. This can cause dangling/null pointers, so really it has to be managed from outside. See this answer outlining that problem in more detail.

---

P.S. Aside from the usual "Singletons are terrible" type arguments (which are terribly dogmatic), have you ever seen a good argument against ResourceManagers? "Dedicated Manager classes are almost never the right engineering tool" is no argument at all *for this specific case*.
> 4 votes

---
Tags: architecture, design-patterns, resource-management
---


# Question
Title: What does the graphics card do with the fourth element of a vector as the final position?
From this question it appears you would want a four-element position vector, as it is simpler to modify its position with matrix multiplication.

On its own this would imply the fourth element should simply be ignored when considering it as a representation of a 3D point (assuming no transformation), but I know this is not true, as when I supply a vector4 to the GPU, if the fourth element is not one, it is not rendered - why?

What is the significance of the fourth element, once it is in the rasterizer?

***EDIT****: On review this question was somewhat poorly worded; it would be more accurate for the second paragraph to say: "if the value of the fourth element is not within a certain range, it is not rendered 'correctly'/'as expected'".*

# Answer
> 25 votes
The fourth component is a trick to keep track of perspective projection. When you do a perspective projection, you want to divide by z: x' = x/z, y' = y/z, but this isn't an operation that can be implemented by a 3x3 matrix operating on a vector of x, y, z. The trick that has become standard for doing this is to append a fourth coordinate, w, and declare that x, y, z will always be divided by w after all transformations are applied and before rasterization.

Perspective projection is then accomplished by having a matrix that moves z into w, so that you end up dividing by z. But it also gives you the flexibility to leave w = 1.0 if you don't want to do a divide; for instance if you just want a parallel projection, or a rotation or whatever.

The ability to encode positions as w = 1, directions as w = 0 and use the fourth row/column of a matrix for translation is a nice side benefit, but it's not the primary reason for appending w. One could use affine transformations (a 3x3 matrix plus a 3-component translation vector) to accomplish translation without any w in sight. (One would have to keep track of what's a position and what's a direction, and apply different transformation functions to each; that's a bit inconvenient, but not really a big deal.)

(BTW, mathematically, vectors augmented with w are known as homogeneous coordinates, and they live in a place called projective space. However, you don't need to understand the higher math to do 3D graphics.)

# Answer
> 10 votes
Tring to answer to the appropriate comment of Natan, I did some consideration that can be useful to understand what really happens when you use vectors in Affine Space to represent 3D vectors in the standard Euclidean Space.

First I will call **vector** whatever has coordinates, so a point and a vector are the same entity; you can see a vector as difference of two point: **V** = **B** \- **A**; **V** moves **A** in **B** because **A** \+ **V** = **A** \+ **B** \- **A** = **B**. Put **A** = **0** (the origin) and you will get that **V** = **B** \- **0** = **B**: the point **B** and the vector that moves **0** to **B** are the same thing.

I will call **"vector"** \- in the sense used in the majority of 3D libraries - when a vector of the affine space has w = 0.

The matrix are used because they let you to represent a linear function in a compact/elegant/efficient form, but linear functions has the major disadvantage that can't transform the origin: F(**0**) = **0** if F wants to be linear (amog other thing such F(λ**X**) = λF(**X**) and F(**A** \+ **B**) = F(**A**) + F(**B**) )

This means that you can not construct a matrix that do a translation since you will never move the **0** vector. Here comes into play the **Affine Space**. The affine space adds a dimension to the euclidean space so traslantions can be done with scaling and rotations.

The Affine Space is a projective space in the sense that you can construct a equivalence relation between Affine and Euclidean vectors so you can confuse them (as we did with poins and vectors). All the affine vectors that projects to the origin with the same direction can be seen as the same euclidean vector.

This means that all the vectors that have the same proportions in the coordinates can be considered equivalent:

Mathematically:

i.e. every affine vector can be reduced to a canon version where w=1 (we choose among every equivalent vector the one we like best).

Visually (2D euclidean - 3D affine):

hence the mean of **"projective"** space; You should notice that here the euclidean space is 2D (the cyan region)

There is a particular set of affine vectors that can't be put in their canonical version (with ease) the one that lies on the (hyper)plane w=0.

We can show it visually:

what you (should) see is that while w -\> 0 then the projected vector into the Euclidean space goes to the infinite but to the infinite in a particular **Direction**.

Now is clear that adding up two vectors in the projective space can lead to problems when you consider the sum vector as a projected vector in the euclidean space, this appends because you will sum the W components in the affine space and then project them to the euclidean (hyper)plane.

This is why you can sum only "points" to "vectors" because a "vector" will not change the w coordinate of the "point" this is true only for **"points"** where w =1:

As you see the green point is the one obtained adding the two affine vectors that represent the cyan **"point"** and the **V "vector"**, but if you apply **V** to every affine vector in a form different by the canon one, you will obtain a wrong results (the red ""point"").

You see that **Affine Space can't be used transparently** to describe operation on Euclidean Spaces and the **misuse of the term "vector"** has sense under the (strict) constraint of compute sums **only** on **canon projective vectors**.

Said that, is quite reasonable to think that the GPU assumes that a **Vector4** has to have w=0 **or** w=1, unless you really know what you are doing.

# Answer
> 1 votes
Assume a vector like (x,y,z,w). This vector has 4 components x( x coordinate in space) , y( y coordinate in space), z( z coordinate in space) and the interesting and mysterious w component. Actually most 3d games operate in 4d space.It is also called 4d homogeneous space. There are some obvious benefits of it -\>

1\> It helps us in combining matrices of translation and rotation into one.But you might be thinking what's the use of it we could just multiply translation and rotation matrix and that's it but no there's more to it.If we don't have the w component in all our vectors then when we multiply the 3d vector(xyz) to the combined matrix of translation and rotation in whatever way we will be unconsciously scaling the values with x,y or z( that's how matrix multiplication operates) and this will probably corrupt the position matrix (translation part of combined matrix) due to scaling.To correct this problem 4th component vector is introduced and this component of the vector(w) will hold value 1.0 in 99% of the cases.This 4th component allow us to have unscaled position values(translation).The matrix is represented as-\>

```
 [x y z w] [rx1 rx2 rx3 1]
           [ry1 ry2 ry3 1]
           [rz1 rz2 rz3 1]
           [px  py  pz  1]

```

and then we have the simple yet powerful matrix. :)

2\> We copy the z value into w component in the perspective projection stage and divide the x,y with it.This way objects become shorter as they move away from screen.

---
Tags: mathematics, graphics, rendering
---


title: Question about "Entity System" design

text:
# Question
Title: Question about "Entity System" design
I am developing a top down 'thing' in SFML and C++ and was wondering about how best to handle so called Entities in my game.

An entity, for example is defined by me as an object in-game, such as a door to a house, that can be interacted with, can be animated, can act on user input, can be affected by physics etc.

I was thinking of handling this system by a series of classes and subclasses.

For example, the base class of Entity would contain the methods `Render`, `Update`, `HandleInput` and such as these are the most basic methods that all entities will contain. Variables of the main class could include `isVisible`, `isPhysical`, `drawDepth` and so on.

A new class for `MapObject` would use inheritance to take the methods from Entity and may also add other methods and variables such as `tileTexture`, `tileHeight` and `tileWidth`.

Abstracting(?) from that again could be the `DoorTile` class which would handle the item specific level of input handling and interaction.

Is this a valid way to handle objects in-game? Are there and glaring errors?(Bear in mind I've been awake for many many hours :p)

Sorry if this is somewhat long-winded, I wanted to be specific as to how my proposed system would work.

# Answer
The real problem with your approach is class proliferation. See Mick West's seminal article on why CBEs (component-based entities) are better. Also see Wikipedia. A quick example for a game is as follows:

Given a space shooter where you can pick up combinations of different equipment and powerups, consider the following:

* You pick up the Ooze Cannon (weapon slot).
* You pick up the Ablative Armour (armour slot).
* You purchase the Ion Emission Drive (engine slot).
* You lose your starting Newbie Radar in combat (radar slot).
* You pick up the Garbroozian Nat Swaffler (miscellaneous slot).
* You swap your Ooze Cannon for a Laser Cannon.

All of these slots are defined "roles" for your game's ships. In order to reliably perform key operations on each of these components (eg. weapon.fire(), radar.ping(), etc.) you have have a known method in a known place, to call. Through inheritance, this looks something like `player.fireWeapon()` or `player.pingRadar()`. So far, so good.

Now every time you add (or remove) a component, you then have to extend (or de-extend!) the player entity class. In order to do this, you need a proliferation of different combinations, eg. OozeCannonAblativeArmourIonEmmisionDriveShip, vs. LaserCannonAblativeArmourIonEmissionDriveShip, to modify implementation of just one component(!).

With object composition instead of inheritance for such cases, you instead have one generic entity class that carries (usually public) data members for each role/slot. So you have weaponSlot, engineSlot, and so on. Then you can just call `player.weapon.fire()`, (you could wrap this as `player.fireWeapon()` -- which will call `this.weapon.fire()`, or do nothing if the weapon slot is empty).

Only use inheritance where you know there will be no such proliferation. A good example of where to use inheritance in games is utility classes, for example a RemoteConnection class that could take one of many forms, eg. TCPConnection, SerialPortConnection.
> 9 votes

# Answer
Highly recommended: a component-based system. There's a lot more information available online. I personally think it's a much better approach for games.
> 3 votes

# Answer
This is a valid way to handle entities. That is, it would function. And this is the traditional way it's done in many engines.

That doesn't mean it is good.

Inheritance-based entity systems tend towards very fat interfaces. You often have a base class that has all of the properties of the derived classes, even though some of them don't make sense on some objects.

Consider a containment-based system. For example, entities aren't renderable; they instead *store* renderable objects. The rendering system would have the list of objects, and all entities would do is maintain the position of those renderable objects. Renderable objects would also be owned by the render system, so they will get rendered when the render system is rendered.

Similarly, the relationship between entities and AI should be that the entity stores an AI. AI's control entities. An entity should not handle "input"; the player should have an AI, which during the AI update is given input. And the player's AI would interpret this input and control the player entity.

Just something to consider.
> 1 votes

---
Tags: architecture, entity-system, sfml
---


title: HLSL Translucent Plastic Shader

text:
# Question
Title: HLSL Translucent Plastic Shader
I'm trying to produce a shader to replicate a white plastic object with a colored light inside. Either by having a shader that will be translucent and if I put a light inside the object the light will show through or by having a shader that fakes the effect of a light inside.

The effect im going for is kinda like a light going through a lamp shade similar to these pictures:

Ideally I would be able to control the strength and colour of the light to get it to pulse and rotate through some nice bright fluro colours

Though I'm not sure where to start!

My question is does anyone know the techniques I should be researching to be able to produce such a shader or have an example of the same/similar shader I can use as a starting point? Or even if you want to provide a shader that might do the job

# Answer
This is an effect known as "Sub Surface Scattering."

There is an example screen space implementation of this in the book "GPU Pro: Advanced Rendering Techniques" that is suitable for real time use.
> 10 votes

# Answer
I don't know HLSL so I can't give an exact answer. What you basicly can to do is set the color of each fragment depending on the distance from the lightsource (ignoring any self shadowing).

In pseudocode it would be something like this:

fragment\_color = light\_intensity * transparency\_color * lightsource\_color / (attenuation * distance\_to\_lightsource^2)

You might also want to use a linear attenuation factor in addition to the squared to get the light to spread out more.
> 0 votes

# Answer
Does the light need to be able to move, and does the object need to be able to deform/animate? If neither of these is the case, a cheap way to do this would be to apply a monochrome texture map on the object that acts as a mask for the light; in the shader you'd sample this texture, multiply it by the current light color/strength and add to the output color.

The obvious follow-up question is how will you generate this texture? You could try painting it, if you have access to an artist or can paint textures yourself. It could also be rendered by an offline tool using raytracing or some such. I'm not familiar enough with raytracing tools to tell you in detail how to set that up, though.

A different approach might be to write a shader that samples the light behind it, using the reversed surface normal in the regular Lambert diffuse shading equation; then you'd multiply it by some mask factor like 0.5 or so and add to the output color. This would allow dynamically moving the light or geometry, and require no textures, but you probably wouldn't get results as good-looking as an offline render.

Regarding subsurface scattering: I don't think that's precisely what's wanted here because all the SSS algorithms for graphics I've seen are designed for light that comes from *outside* the surface, bounces around a bit and exits again, while here the light is *inside*.
> 0 votes

---
Tags: graphics, shaders, hlsl
---


# Question
Title: Meshes crashed memory from CharacterCustomization example
I am trying the CharacterCustomization example from Unity3D which contains two scenes: Dressing room and VirtualWorld, run the VirtualWorld on iPhone, it could run but at last it will crashed, Instruments and profiler, I found the meshes are always increased and run out of memory. Anybody could help? thanks.Environment: Unity 3.4.0, Xcode 4.0.2, iOS SDK 4.3

# Answer
> 1 votes
Just guessing here, but the procedural meshes and/or textures it puts together probably aren't getting destroyed.

Art resources loaded at runtime in Unity cannot be garbage collected because it doesn't know that it might be used again.

---
Tags: iphone, unity
---


# Question
Title: Everything "invisible" when launching map from launcher
I downloaded the CryENGINE SDK, and I tried the map Forest from within the editor and it worked fine. However, if I launch it from the Launcher using the console it looks like this:

I can use the weapons (although they are invisible) and interact with objects despite not seeing them. I also did my own map and had the same problem. What am I doing wrong?

# Answer
> 1 votes
I think CryEngine probably compile shaders ( this in CryEninge can take a lot of time ) or engine have some problems with compiling shaders. Look in the log.

---
Tags: cryengine
---


# Question
Title: Documentation/Spec for Flash's XFL layout?
Has anyone found an official spec or documentation on the XFL file layout?

Are there any design tools in existence or planned that can create XFL files? (Besides the official Adobe Flash Professional program)

# Answer
> 2 votes
This is a duplicate of the Stack Overflow question, *Where is the documentation for Adobe XFL Flash interchange format?*, in which there is a statement from 2008 saying Adobe "intends" to release the documentation.

It also links to *What's the meaning of the non numerical values in the XFL's edge definition?* which has some details on the drawing commands present in the format.

---
Tags: flash
---


title: Rendering only what is on the screen

text:
# Question
Title: Rendering only what is on the screen
I am fairly new to this world, so bear with me.

I have a grid of blocks in a top-down, 2d game written using Slick. The best way to think of it is the Pokemon world.

Right now, I am rendering all the blocks on a specific map, whether they are on the screen at the time or not.

Is there a better way to do this? My thought was maybe to try creating an image out of what I would have rendered and taking the section that fits the screen to render. I don't know how to do this, but I wanted to consult the experts before I dove into it. Thanks! ;)

**EDIT**

Just thought I would add that Slick has a way of dealing with clipping in specialized cases as well as the screen's viewport. See the Wiki page for more info.

# Answer
> 11 votes
One way to do this is to check the bounding box of the block against the bounding box of the current view (plus a bit for safety).

If the block interacts with the view (either fully inside or clipped) then draw it. If it doesn't - i.e. is totally outside then don't draw.

This check can be performed quite quickly - particularly in 2D. You don't have to know how much of the block is visible - just that some part of it is potentially visible.

If the **maximum** X coordinate of the block is less than the **minimum** X coordinate of the view or the **minimum** X coordinate of the block is greater than the **maximum** X coordinate of the view then this block is definitely invisible. The same test can be done on the Y coordinate.

As Joe points out in is comment the framework/libraries you are using might have this functionality built in.

# Answer
> 2 votes
Do something like this:

```
if (renderX >= 0 && renderY >= 0
    && renderX <= container.getWidth() && renderY <= container.getWidth()) {
    //Render
}

```

It will have to be custom for each object since every object has a different size. I render each group of components separately. If you're using TiLeD, here's a nice piece of code I made:

```
TiledMap map = mapComp.getMap();

    //Render positions as integers
    int renderX = (int) renderPos.getX();
    int renderY = (int) renderPos.getY();

    //Render offset for map
    int xRenderOffset = renderX % 32;
    int yRenderOffset = renderY % 32;

    //Get the first tile to be rendered
    int firstTileX = (int) -renderX / 32;
    int firstTileY = (int) -renderY / 32;

    //Render tiles only if their indices are greater than 0
    if (firstTileX < 0) {
        xRenderOffset += Math.abs(firstTileX) * 32;
        firstTileX = 0;
    }

    if (firstTileY < 0) {
        yRenderOffset += Math.abs(firstTileY) * 32;
        firstTileY = 0;
    }

    //Get the last tile to be rendered
    int lastTileX = firstTileX + (client.getContainer().getWidth() / 32) + 1;
    int lastTileY = firstTileY + (client.getContainer().getHeight() / 32) + 2;

    //Verify that the last tile is valid
    if (lastTileX > 127) {
        lastTileX = 127;
    }

    if (lastTileY > 127) {
        lastTileY = 127;
    }

    //Check if the map will be visible on the screen
    if (lastTileX >= 0 && lastTileY >= 0) {
        map.render(xRenderOffset, yRenderOffset, firstTileX, firstTileY, lastTileX, lastTileY, 0, true);
        map.render(xRenderOffset, yRenderOffset, firstTileX, firstTileY, lastTileX, lastTileY, 1, true);
        map.render(xRenderOffset, yRenderOffset, firstTileX, firstTileY, lastTileX, lastTileY, 2, true);
        map.render(xRenderOffset, yRenderOffset, firstTileX, firstTileY, lastTileX, lastTileY, 3, true);
    }

```

32 is your tile width, and 127 is your map size - 1.

# Answer
> 1 votes
If your blocks are uniformly sized (as is the case in the classic Pokemon games) and stored in a 2d array, then probably the best way to do this is to just do for-loops, something like this:

```
int startX = playerX - halfWidth;
int startY = playerY - halfHeight;

for( int x = startX , maxX = playerX + halfWidth; x < maxX; ++x )
{
    for( int y = startY , maxY = playerY + halfHeight; y < maxY; ++y )
    {
        DrawBlock( x - startX, y - startY, tiles[x][y] );
    }
}

```

where halfWidth and halfHeight are half the width and height of the screen respectively. This will cut the calls to DrawBlock down to only those that are visible. If you are scrolling around the grid, then you can draw an extra tile in each direction and add your animated offset values to the DrawBlock parameters as needed.

It should be mentioned that this method is complementary to the method of clipping that you linked to in your edit. Using the method I've presented here, clipping would be useful if your blocks shouldn't take up the entire screen (e.g. there is a border around them for a User Interface), to prevent extra blocks that are being drawn for animation purposes from being drawn over other elements. In this case, you would set your clipping region to be exactly the space where you want your grid to be displayed, and then draw only the minimal blocks necessary.

---
Tags: 2d, java, lwjgl, slick
---


# Question
Title: how to get started making games with java
I was wondering how could I get started making games with java? I tried looking up tutorials but I couldnt find any ,also if I make a game with java and it connects to a database would someone be able to decompile the game and see the stuff to connect to the database

# Answer
Check out LWJGL, and it's documentation (teaches you the basic stuff). Minecraft uses the same library.
> 3 votes

# Answer
Looooong time ago, when I was trying to start programming with Java, I followed a tutorial to create a simple Space Invaders in Java. I am pretty sure that there are much new (and better?) tutorials currently available on the net, but just in case... **this** is the tutorial I followed. It has 27 lessons that you can follow, and at the end you end up with a nice Space Invaders :)
> 2 votes

# Answer
Since you're interested in making a game and not building an engine you may want to look at Java Monkey Engine and head straight to their tutorials Tutorials

You didn't mention how experienced you are at coding in Java but you will want to either look at tutorials in OpenGL for 3D work or research Tile engines for 2D.
> 1 votes

# Answer
Check out LWJGL with Slick.
> 0 votes

---
Tags: java
---