dev in the making

game development, maya and code by brainzizi

Posts Tagged ‘projects

zAnimation – a simple XNA animation library

with 3 comments

Before XNA 3.1, there was a bunch of animation frameworks which could to tons of stuff like interpolation between animations and stuff like that. When the 3.1 came out all of these became obsolete – except kw animation which comes with a 3ds max exporter and is great if you’re using max, but I’m using Maya and I needed to write my own animation foundation. zAnimation is a XNA library for animating skinned models exported from Maya. It supports customizable pre-clip interpolation, and per-bone animation. No interpolation between frames or animations yet.

Pre-clip interpolation:

Before a clip is played, the model interpolates over a customizable number of frames to the starting position. It delays an animation a bit but removes jerky transitions between animations.

Per-bone animation:

When defining a clip within the animation, you also define what bones does the clip affect. Based on that you can play an animation that animates all the bones in a model, and easily override the animation on one or more bones to make them move in a different way.

Below I’m listing a couple of things that I encountered while writing zAnimation:

Maya gets all your animation keyframes and exports it in a single take called “Take 001”.

To deal with this I introduced another file (the take definition file) which contains where does a certain animation start and end, and also what bones does it affect.

XNA FBX Importer removes redundant bones.

If a bone has no weights defined on a skin it gets deleted. The same thing happens if the bone doesn’t move (change) in the keyframes. So I introduced 2 special parts of the animation, the “Bind” part and the “Init” part. The bind part acts like a starting transform, and the init part is just there so you don’t forget that you have to animate a bone if you want to have it.

So based on that there are a few rules and limitations to zAnimation:

– smooth binding only

– each bone in each skin has to have some weights, so no root bones with no weights (or it won’t be imported as a bone)

– each bone has to have at least 2 keyframes that are not the same (or it won’t show up in the keyframes at all)

– strictly defined animation timeline:

-at frames 0 and 1 keyframe every bone at its bind pose position. This is the position your animation starts with.

-at frame 3 you should keyframe every bone it any position other than its bind pose. I select all my bones and rotate them in the x-axis about 45 deg.

-at frame 4 you should keyframe your bind pose again.

– after frame 4 animate your model as you wish

– when importing a model create a takes.def file in the same directory as your exported fbx is in the XNA content folders, set its build action to none from Visual Studio

– takes.def file has a specific structure that is line delimited, so the first line should look like this:

Bind, 0, 2, AffectedBone0, AffectedBone1, AffectedBone2

and each line after that should look like this:

AnimationName, StartFrame, EndFrame, AffectedBone0, AffectedBone1, AffectedBone2

here’s an example of a takes file

Bind, 0, 2, root, door
Open, 4, 34, door
Opened, 34, 36, door
Close, 36, 66, door

That’s more or less it. I’ll release it on codeplex in a couple of days. Check it out if you’re a XNA developer working with Maya.


Advertisements

Written by brainzizizi

11.05.2009 at 08:52

Posted in xna

Tagged with , , , ,

Abandoned: Terrain

leave a comment »

I’m building a little game called Abandoned, and I’ve just taken the first step and built the terrain. I used Shawn’s excellent article about detail textures found here. It’s just a simple terrain, but the colors and the fog settings have a huge impact of the atmosphere in the game. Even though it’s flat, I’ve built the vertices and indices as a little grid, maybe I decide later to have a heightmap or something. I’ve encountered one problem so far, and that’s poor texture quality. Then I remembered something about mipmaps and turned on their generation on the content pipeline options, and the problem disappeared. The result:

I wish to share my terrain generation function that I’ve been using for a while now (I probably stole it from somewhere, I just can’t remember where). It’s good for heightmaps and flat terrain alike. The size is an int because its the number of rows and columns, size of CellSize in the terrain grid.

void Build(int Size, float CellSize)
{
Debug.WriteLine(“Building ground vertices and indices. Size: ” + Size + “, CellSize: ” + CellSize + “.”);
vertices = new VertexPositionTexture[(Size + 1) * (Size + 1)];
indices = new int[Size * Size * 6];
for (int i = 0; i < Size + 1; i++) { for (int j = 0; j < Size + 1; j++) { VertexPositionTexture vert = new VertexPositionTexture(); vert.Position = new Vector3((i - Size / 2.0f) * CellSize, 0, (j - Size / 2.0f) * CellSize); vert.TextureCoordinate = new Vector2((float)i / Size, (float)j / Size); vertices[i * (Size + 1) + j] = vert; } } for (int i = 0; i < Size; i++) { for (int j = 0; j < Size; j++) { indices[6 * (i * Size + j)] = (i * (Size + 1) + j); indices[6 * (i * Size + j) + 1] = (i * (Size + 1) + j + 1); indices[6 * (i * Size + j) + 2] = ((i + 1) * (Size + 1) + j + 1); indices[6 * (i * Size + j) + 3] = (i * (Size + 1) + j); indices[6 * (i * Size + j) + 4] = ((i + 1) * (Size + 1) + j + 1); indices[6 * (i * Size + j) + 5] = ((i + 1) * (Size + 1) + j); } } vb = new VertexBuffer(GraphicsDevice, (Size + 1) * (Size + 1) * VertexPositionTexture.SizeInBytes, BufferUsage.None); ib = new IndexBuffer(GraphicsDevice, 6 * Size * Size * sizeof(int), BufferUsage.None, IndexElementSize.ThirtyTwoBits); vb.SetData(vertices); ib.SetData(indices); Debug.WriteLine("Finished building ground vertices and indices.");} [/sourcecode]

Written by brainzizizi

08.18.2009 at 10:41

Posted in xna

Tagged with , , , ,

zCamera on codeplex

with 4 comments

It’s all here: http://zcamera.codeplex.com.

Please post your feedback either here, on codeplex, or on my email.
Looking for XBOX developers for testing and rewriting the code for XBOX.

Written by brainzizizi

08.17.2009 at 07:31

Posted in xna

Tagged with , , , ,

zCamera: Extensibility

leave a comment »

I like to think zCamera is very extensible. Is it really? Maybe, you’ll have to try.
The whole project consists of a really small number of .cs files:

zCameraManager.cs

The main file, inherits from DrawableGameComponent, so I can get to Game.Content and Game.GraphicsDevice for debugging purposes. Most important thing in this file is a list of all cameras of type zBaseCamera.

zVectorRenderer.cs

Vector renderer I got from www.ziggyware.com, and reworked so it’s no longer a GameComponent, but the zCameraManager takes care of it. And added support for drawing bounding frustrums.

zCameraKey.cs

The data structure used for saving keyframes. Also inludes the zInterpolationType enum for choosing position and focal distance interpolation.

Cameras\\zBaseCamera.cs

Abstract class, stores the shared fields and methods of all cameras, like position, view, projection, aspect ratio, forward vector, name, set target method, etc. If you want to build your own camera and manage it through the manager, inherit from this class. Also it contains basic debug drawing code which might also be very handy and Save/Load functions where you can save a camera using the Intermediate Serializer, and load it later as an xml converted to xnb through the pipeline, and a load function which loads raw xml files structured like the file the Save method outputs.

Cameras\\zBaseKeyframedCamera.cs

Also an abstract class, inherits from zBaseCamera and has build in keyframe support using 2 lists: List<TimeSpan> Keys and List<zCameraKey> Values. I tried using a Dictionary for this, but it just didn’t work out, due to the inability of getting a value by index, and I think this is more C++ like. Not that that’s a good thing, but I don’t think it’s gonna be a problem.

This class has support for keyframes. That means interpolation and keyframe following. I have one known bug/feature here, and that’s a bit of a hiccup when translating between the last and the first keyframe when repeat is on. The last keyframe is in fact getting linear interpolation in and out of it, because I don’t pass in the keyframes from the beginning into the catmull rom function. Maybe a little annoyance, but no showstopper.

If you want to build a cinematic camera this is the class to inherit from. Also has support for waypoint debugging and save/load

Various Helper files

Containing some helpful extension methods and interpolation functions.

And that’s about it! I’d love to post some screens but as this project is not really eye candy I’ll refrain myself.

Written by brainzizizi

08.11.2009 at 17:11

Posted in xna

Tagged with , , ,

zCamera Save/Load

leave a comment »

Hi!

On my zCamera project, I’ve added basic support for saving and loading.
The zBaseCamera, the base class of every camera provides this interface:

public virtual SaveSettings(string path);
public virtual LoadSettings(string path);

Save is done using the IntermediateSerializer, and load is done using XmlReader to support raw .xml loading.
See, the IntermediateSerializer output needs to be compiled at runtime in order for you to load it during your game. So no save/load sessions using just the serializer.

        /// <summary>
        /// Saves the camera settings.
        /// </summary>
        /// <param name="path">The path of the file to write, without the extension.</param>
        public virtual void SaveSettings(string path)
        {
            XmlWriterSettings settings = new XmlWriterSettings { Indent = true };

            string fullPath = manager.Game.Content.RootDirectory + "\\" + path + ".xml";
            if (File.Exists(fullPath))
                File.Delete(fullPath);

            XmlWriter writer = XmlWriter.Create(fullPath, settings);
            IntermediateSerializer.Serialize(writer, this, null);
            writer.Close();
        }
        /// <summary>
        /// Loads the camera settings.
        /// </summary>
        /// <param name="path">The path of the file to read, without the extension.</param>
        public virtual void LoadSettings(string path)
        {
            XmlReader reader = XmlReader.Create(manager.Game.Content.RootDirectory + "\\" + path + ".xml");
            while (reader.Read())
            {
                if (reader.Name == "Name")
                    Name = reader.ReadElementContentAsString();

                if (reader.Name == "Debug")
                    Debug = reader.ReadElementContentAsBoolean();

                if (reader.Name == "FocalDistance")
                    FocalDistance = reader.ReadElementContentAsFloat();

                if (reader.Name == "FieldOfView")
                    FieldOfView = reader.ReadElementContentAsFloat();

                if (reader.Name == "AspectRatio")
                    AspectRatio = reader.ReadElementContentAsFloat();

                if (reader.Name == "NearPlaneDistance")
                    NearPlaneDistance = reader.ReadElementContentAsFloat();

                if (reader.Name == "FarPlaneDistance")
                    FarPlaneDistance = reader.ReadElementContentAsFloat();

                if (reader.Name == "Position")
                {
                    string vector = reader.ReadElementContentAsString();
                    Position = zCameraHelper.ParseFromIntermediateSerializer(vector);
                }
            }

I’ll release the complete source next week.

Written by brainzizizi

08.11.2009 at 07:09

zCamera keyframes and interpolation

leave a comment »

In my camera keyframe following project, I’m using this structure to record keyframes:

TimeSpan Key;
Vector3 Position;
Quaternion Rotation;
float FocalDistance;
zInterpolationType PositionInterpolation;
zInterpolationType FocalDistanceInterpolation;

I’m saving these in 2 lists, one containing the timespan, and the otherone containing zCameraKey (which contains other data from the previous code).

When interpolating between those keyframes you have to be sure it’s first of all smooth. This is a bit harder to achieve, considering you must interpolate 3 things: position (vector3), rotation (quaternion) and focal distance (float). The results are done smoothest with the following: Position interpolation is done using Catmull-Rom XNA built in function. Rotation is interpolated using Slerp – also XNA built in, and focal distance also Catmull-Rom. But the smoothness can be still broken with keyframes with variable distance / time ratio. Why? Because of the speed of change. This can be dealt with, but I should change my entire keyframe following system to achieve that, so I’m giving that up. The designer or whoever is setting up animation cameras should take care of that.

As the saying goes: That’s not a bug. That’s a feature.

Yeah… Because you now control the speed of change. Not some silly algorithm. If you want a smooth camera that doesn’t care about the spacing of the keyframes, use Graphic Runner’s Camera animation @ http://graphicsrunner.blogspot.com/2008/05/camera-animation-part-ii.html.

Also I frapsed some keyframe following action in low res on youtube, check it out: http://www.youtube.com/watch?v=seUiYPo_V1k

Also a couple of the latest screens from zCamera:

Written by brainzizizi

08.09.2009 at 21:00

Posted in xna

Tagged with , , , ,

zCamera

leave a comment »

I’m having a blast playing with camera code in XNA. This is the third time I’m writing my own camera, and after I experimented a bit with various camera implementations including Quaternion rotation, Matrix rotation, frame-by-frame rotation, I can now say that I get the basic principles of every camera. And my goal is to make a light camera framework, with a couple of build in cameras and code for easier writing your own camera. Last night was really productive, as I wrote some messy debug code using the vector renderer component from Ziggyware which I’ve tweaked a bit to draw bounding frustrums and alike.

I’ll release the source when I write some more camera types, but first a couple of screen shots:

The package will consist of two projects: zCamera and zCameraPlayground which uses an early version of zGui, my gui framework for debugging purposes.

PS.
The model I used is the model from XNA’s Normal Map sample. If you see a problem in that, please leave a comment.

Written by brainzizizi

08.08.2009 at 12:22

Posted in xna

Tagged with , , , , , ,