Archive for the 'Framework' Category

Skeletal Animation in 2D (Part 2: Construction)

Okay so here’s an update on my implementation on skeletal animation in 2D… Basically… it works! :D

Above are some screenshots showing skeletal animation working hand in hand with the scenegraph I programmed for Project Warpy. These are some of the first development screenshots I’ve actually posted and although I’m not supposed to reveal game-play, I should be able to release screenshots as long as they do not reveal game-play (such as these).

Okay so first things first, how does the skeletal animation actually work:

  1. Create skeletal animation in maya
  2. Export to .X format
  3. Parse .X format with XNA’s X importer
  4. Custom processor to serialize bones and animations
  5. Parse bone transformations and convert to scenegraph
  6. Animation controller updates the bone nodes
  7. Interpolate between keyframes
  8. Attach sprites to bone nodes

Voila! This technique closely mimicks rigid binding and requires some knowledge of matrices and hierarchical transformation.

So before you can get any bone animation working in 2D you’ll need some kind of hierarchical system (in my case, a scenegraph). I create “nodes” that contain position, scale and rotation and use the following formula to obtain a transformation (in world space).

transform = Matrix.Identity;
transform *= Matrix.CreateScale(new Vector3(scale.X, scale.Y, 1));
transform *= Matrix.CreateRotationZ(rotation);
transform *= Matrix.CreateTranslation(new Vector3(position.X, position.Y, 0));
transform *= parent.transform;

transform represents the transformation matrix of the current node in world space. It is created by multiplying the local scale, rotation and translation followed by its parent’s transformation. This is done down the hierarchical chain (with parent first multiplying its transformation, followed by its children) just prior to rendering. The result is nodes that translate, scale and rotates according to its parent’s transformation, in layman terms, when the parent moves the child node moves in accordance.

Because bones are usually stored with transformations relative to its parent bone its easy to adapt it to such a system and therefore the only thing I do in the model processor is read in bones and animations and decompose the matrix into translation, rotation and scale (as used later in the application described above).

// process the bindpose matrices..
for (int i = 0; i < bindPose.Count; i ++ )
{
    Vector3 trans, scal;
    Quaternion rot;

    bindPose[i].Decompose(out scal, out rot, out trans);

    float rs = (float)Math.Sqrt(rot.X * rot.X + rot.Y * rot.Y + rot.Z * rot.Z);

    // make sure we dont get a divisable by 0 error.
    if (rs == 0)
        rs = 1;

    float z = rot.Z / rs;
    float angle = 2.0f * (float)Math.Acos((double)rot.W) * z;

    this.bindPose.Add(new Transform(new Vector2(trans.X, trans.Y), new Vector2(scal.X, scal.Y), angle));
}

I also store a list of parents for each bone, so I know how to parent them after they are loaded:

IList<BoneContent> bones = MeshHelper.FlattenSkeleton(skeleton);

foreach (BoneContent bone in bones)
    hierarchy.Add(bones.IndexOf(bone.Parent as BoneContent));

Once these values are stored the skeleton simply has to be reconstructed using the nodes in the scenegraph.

// contains a list of attached joints.
joints = new List<SkeletonJoint>();

// constructs the bones straight away!
for (int i = 0; i < data.bindPose.Count; i++)
{
    SkeletonJoint joint = new SkeletonJoint();
    joint.position = data.bindPose[i].translation;
    joint.rotation = data.bindPose[i].rotation;
    joint.scale = data.bindPose[i].scale;
    joints.Add(joint);
}

// go through that list again to parent joints..
for (int i = 0; i < data.hierarchy.Count; i++)
{
    // check if this is the root joint..
    if (data.hierarchy[i] == -1)
    {
        addChild(joints[i]);
    }
    else
        joints[data.hierarchy[i]].addChild(joints[i]);
}

Now that the skeleton is built (in your scenegraph), the only thing left to do is animation! I will be releasing an article describing keyframe animation and interpolation in part 3 of the article. Hope you enjoyed reading this.

p.s. This article has been left intentionally vague, sorry for not publishing complete code samples but there shouldn’t be a problem implementing this if you get the theory! :P

Input Action Mapping

One interesting way to generalize input in games is known as action mapping. Basically instead of keys (or buttons) being pressed or released, objects react to when actions are “pressed” and “released”. The largest benefit of using this method when programming input for games is when your project requires input from multiple devices (or support for multiple devices in the future).

Actions are generated from device handlers and propagated to game objects for evaluation. Device handlers handle input device events (such as key press/release) and create the corresponding action.

This worked especially well when developing Project Warpy for the XBOX/PC as debugging on the PC requires keyboard input, while the XBOX only accepts controller input.

Here’s a quick snippet on how you can implement this into your own games:

enum Action
{
    MOVE_LEFT,
    MOVE_RIGHT,
    JUMP
};

class KeyboardHandler
{
public:
    void onPress(char key)
    {
        if (key == LEFT_ARROW)
            gameWorld.propagateKeyPress(MOVE_LEFT);
        if (key == RIGHT_ARROW)
            gameWorld.propagateKeyPress(MOVE_RIGHT);
    }

    void onRelease(char key)
    {
        if (key == LEFT_ARROW)
            gameWorld.propagateKeyRelease(MOVE_LEFT);
        if (key == RIGHT_ARROW)
            gameWorld.propagateKeyRelease(MOVE_RIGHT);
    }
};

Of course, this is not very useful if you only need support for 1 type of input device. But… say I wanted support for the XBOX 360 controller.

class ControllerHandler
{
public:
    void onPress(Button button)
    {
        if (button == DPAD_LEFT)
            gameWorld.propagateKeyPress(MOVE_LEFT);
        if (button == DPAD_RIGHT)
            gameWorld.propagateKeyPress(MOVE_RIGHT);
    }

    void onRelease(Button button)
    {
        if (button == DPAD_LEFT)
            gameWorld.propagateKeyRelease(MOVE_LEFT);
        if (button == DPAD_RIGHT)
            gameWorld.propagateKeyRelease(MOVE_RIGHT);
    }
};

This works for any device (or device library for that matter) as long as propagateKeyPress and propagateKeyRelease are called in the right place and because the game objects react to the Action enum, no extra coding on the game object side is required.

Skeletal Animation in 2D (Part 1: Concept)

Sometime last year I was playing the game patapon for the psp. Impressed by the fluid animation I tried to look for the technique utilized by the game to perform it’s character animations. I guess my search terms must have been wrong because I couldn’t find any viable results. Half a year later I stumbled across Patapon DS a homebrew version of patapon for the DS, and this post, in particular, caught my attention.

After examining the animation technique presented in that post, I was left thinking: “This seems awfully familiar” and before I knew it I decided to try skeletal animation in 2D (like patapon). My first experiment consists of loading .X models (with only bones exported) and using these bones as entities in a 2D scene graph.

So here’s the motivation factors of this technique:

  • Easy to deploy (Information on bone transformation and .X file format easy to obtain)
  • Easy to create content (No special animation tool or file format required, just a .X exporter)
  • Easy to integrate (Since bones function similarly to parent-child scene-graphs)

This technique, if successful, will be utilized in project warpy for enemy animations.

Hierarchical Based Systems

Programming complex game scenes often leads to very large and unmodular classes. During my years as a game programmer, one of the systems I’ve discovered to solve this problem is Hierarchical Based Systems. In fact, some languages are even centered around this ideology, namely flash as3!

Structure of a Hierarchical System

So what exactly is a hierarchical based system? Well simply put, a scene is divided into nodes where each node is a useful object that “exists” in the scene. One can say nodes are modular logic code. The basic rule of a node, in my opinion, is that it must have a parent and a set of children. The node first runs it’s own logic followed by all its children logics. Therefore just by calling the root node’s logic functions, all its children (and their children too) have their logics called automagically.

Here’s an example of a game component:

class Component
{
public:
  std::list<Component*> children;

  void addChild(Component* component)
  {
    children.push_back(component);
  }

  void removeChild(Component* component)
  {
    children.remove(component);
  }

  virtual void update()
  {
  }

  void _update()
  {
    update();
    for (std::list<Component*>::iterator i = children.begin(); i != children.end(); i ++)
      (*i)->_update();
  }
};

This class serves as a template, where inheriting classes just have to modify the update() function. The framework programmer then calls _update() to update the object and all its children down the hierarchy.

As if this wasn’t useful enough, nodes can further improve coding in games by providing the platform for scene management techniques, such as scene-graphs and octrees. But more on that another time. :P