Sign Up NOW to get 100 free credits, used to download 3D Models, Textures, Sound Effects and Music!

Lesson 27: Direct3D 11 Animating MD5 Models (Skeletal Structure)

Introduction

This is the second lesson of our md5 lessons. In the last lesson we talked about just loading the md5 model, and using the skeletal system to compute the vertex positions and normals. In this lesson, we will learn how to load in the md5 animation file ".md5anim", and use the data stored in this file to animate our model.

I'm aware that my modeling skills are poor, but i'm planning on improving them soon. I think after this lesson I'll get a real server and a real domain name, haha, then start to work on the other parts of this site (forum, audio, vision).


Animating the Model (Using the Joint Structure)

We briefly covered skeletal animation in the last lesson. So now we will focus on how to use the skeletal structure (joints) to animate a model in this lesson. We can take this in steps.

First we will load in the animation file (.md5anim), which we will cover below. After that, we need to compute the skeleton based on the current time in the animation. We can do this by "interpolating" two skeletons based on the current time between two frames (the frame thats already passed, and the frame thats coming up). After we create the interpolated skeleton, we need to recompute the vertices positions and normals using the weight. Finally, after we have our vertex positions and normals (we can find tangents and bitangents the same way as normals), we need to update our vertex buffer. Basically this is like four steps, where the first step will be covered shortly (loading in the animation), so we can skip to the second step, creating the interpolated skeleton.


Creating the Interplated Skeleton

When we load in the animation, we create a skeleton for every frame of animation. We can then "interpolate" two of these frames (eg. frame 1 and frame 2) to get the current frame of animation. We could of course just use the frames of animation themselves without creating an interpolated skeleton per frame, but this might look "choppy", and if there is ever a time when time in the game slows down, like in the matrix where you can see the bullets flying, you would have an even more choppy animation.

The animation file also says how many frames per second the animation should run. The model we are loading uses 30 frames per second. We can multiply the current animation time (the time since the beginning of the animation started) with the frame rate, to get the current frame we are on. This calculation will produce a floating point number, for example "5.3667". In this example, "5.3667", we are currently on frame "5", so we can use the function floorf() to round down to the nearest whole number, which is "5" in this case. That is what we will store in frame0, which will be the first of two frame skeletons to interpolate. We can get the second skeleton frame by simply adding "1" to frame0, which gives us frame1, or "6" in the current example. Now we have both the frame skeletons we will be interpolating to find the interpolated skeleton that we will use to update our model, but when interpolating two things, we need a value between 0 and 1 ("0" being all frame0, "0.5" being half frame0 and half frame1, and "1" being completely frame1) to know how much of each thing to use. what value can we use as an interpolation factor? I know, probably a pretty easy question, but we will use the remainder of the value we got above when finding which frame we are one, which in the current example would be "0.3667" (we find this by subtracting frame0 from that value above). Now let's do the interpolating.

Now we find the actual interpolated skeleton. This is actually pretty easy. We loop through each joint of the model (since the animations use the same joints, just at different positions and orientations), and interpolate their positions and orientations. To update their positions, we can use the following equation:


interpolatedJoint.position = joint0.pos + (interpolation * (joint1.pos - joint0.pos))

To find the interpolated orientation between the two frame's joint's, we will use a technique called "Slerp", or spherical linear interpolation. Conveniently, there is an xna math function that will do this for us, so we are able to get the interpolated orientation with the following line:


interpolatedJoint.orientation = XMQuaternionSlerp(joint0.orientation, joint1.orientation, interpolation))

We do the above for every joint, the end result is our interpolated skeleton.


Updating the Vertex Position and Normal

The next thing we need to do is update our vertices and normals using the interpolated skeleton. We can do this basically the same way we got our vertex positions in the last lesson. We loop through each vertex, and in that loop, we loop through each of the vertex's weights positions. We first rotate the weight around the joint using the joints orientation, and the following equation:


weightPos = XMQuaternionMultiply(XMQuaternionMultiply(jointOrientation, weightPos), jointOrientationConjugate))

This will give us the weights position in joint space. We now need to move the weight to the joints position in model space. We can easily do this by adding the joints position to the weights position. Finally, we multiply the weights position with the weights bias factor, and add it to the vertices final position.

We will also be calculating the normal. This hasen't been explained yet, but we will be using the weight's normal (that we got from updating the function where we load the md5mesh file). We will rotate the weights normal the same way we rotated the weights position using the joints orientation. Since normals do not have a position, we do not need to add the joints position to the normal. Then we multiply the weights normal with the weights bias factor, and add it to the vertex's final normal.


Updating Direct3D's Buffers

The last thing we have to do, is update the vertex buffer. There are three ways to do this (one for each type of buffer, being D3D11_USAGE_STAGING, D3D11_USAGE_DYNAMIC, or D3D11_USAGE_DEFAULT. The D3D11_USAGE_IMMUTABLE type of buffer cannot be updated).

The first way is to use a D3D11_USAGE_DEFAULT buffer, with a D3D11_USAGE_STAGING buffer. Staging buffers are used to get information from the buffer that is sent to the GPU, since the default buffer is basically a copy of the staging buffer. To update the buffer, you will first update the staging buffer using ID3D11DeviceContext::Map and ID3D11DeviceContext::Unmap. You will then copy the contents of the staging buffer to the default buffer using ID3D11DeviceContext::CopyResource. The Map method returns a D3D11_MAPPED_SUBRESOURCE object, whose pData member is a pointer to the start of the data in the buffer. We can then use the memcpy() function to store the vertices (or whatever data you want) in the buffer. We can do it something like this:


D3D11_MAPPED_SUBRESOURCE mappedVertBuff;
ID3D11DeviceContext->Map(stagingVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedVertBuff);

memcpy(mappedVertBuff.pData, &vertices[0], (sizeof(Vertex) * vertices.size()));

ID3D11DeviceContext->Unmap(stagingVertexBuffer, 0);

ID3D11DeviceContext->UpdateSubresource( defaultVertexBuffer, 0, NULL, &stagingVertexBuffer, 0, 0 );


The second way to do it is just update the default buffer without using a staging buffer. We only need one line to do this, and it uses the ID3D11DeviceContext::CopyResource method. You can update a default buffer with the following line:


ID3D11DeviceContext->UpdateSubresource( defaultVertexBuffer, 0, NULL, &vertices[0], 0, 0 );


This last way is for a buffer created with D3D11_USAGE_DYNAMIC usage. This is the way we will be updating our buffers, since it's made for fast updating (although it's read a little more slowly by the GPU because of it). We can update this buffer like we did the staging buffer, using Map and Unmap. The following is an example:


D3D11_MAPPED_SUBRESOURCE mappedVertBuff;
ID3D11DeviceContext->Map(dynamicVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedVertBuff);

memcpy(mappedVertBuff.pData, &vertices[0], (sizeof(Vertex) * vertices.size()));

ID3D11DeviceContext->Unmap(dynamicVertexBuffer, 0);


The first and second, using staging and default buffers are updated much more slowly than the dynamic buffer, so you should only do the first two methods of updating a buffer if the buffer is updated LESS than once per frame. The default buffers are read by the GPU faster, and updated slower. The dynamic buffers are read by the GPU slower, but are updated much faster. You can find more information on the types of buffers here.


The .md5anim Format

The .md5anim format is sectioned off into basically five parts: the header, hierarchy, bounds, baseframe, and frames. The header holds information about the file and animation, like frames per second, file version, number of joints and frames total etc. The hierarchy is a list of the joints used in the model. The joints in the hierarchy section should match up in number and parent-child bindings as the .md5mesh file. After the hierarchy is a section called the bounds. This section defines an Axis-Aligned Bounding-Box (AABB) for each frame of the mesh. This AABB can be used for quick and dirty calculations such as collision detection or picking. After the bounds is the baseframe, which stores the position and orientation of each joint in it's default position. All frames will be built off this baseframe, or base skeleton. Finally we have the frames. There is one section per frame, and each section contains a list of floating point values which explain how the joints are to be moved and rotated.


"MD5Version"

Following this string is a number describing the version of the file. Our loader was designed specifically for version "10" (although I decided to skip the actual check in the loader). You can find out information about other version, although every md5 model i've downloaded (which I won't lie, is not many) has been version 10.


MD5Version 10


"commandline"

This line contains something that we will not have to worry about ;)


commandline ""


"numFrames"

This is the number of frames in our animation. This lessons model uses 46 frames of animation, so there will be 46 frame sections in the file.


numFrames 46


"numJoints"

This is the number of joints in our model, and in the hierarchy section. This number should match up with the number in the .md5mesh file.


numJoints 31


"frameRate"

The frame rate is how many frames per second the animation should run. We take this into consideration in our program to make sure we keep a smooth and constant animation at the same speed the file intended it to be.


frameRate 30


"numAnimatedComponents"

This is the number of components, or floating point numbers in each of the frame sections. Each of these components will replace one of the components of the base frame joints position or orientation. This will be described later.


numAnimatedComponents 186


"hierarchy"

This is the start of the joint descriptions. The joint descriptions start on the next line (after "joints {") and go until a line containing a closing bracket ("}") is reached.

The number of the joints, and the parent index and name of the joints must match up with those in the .md5mesh file. If they didn't match up, the animation would have very unexpected results.

Each line after "joints {" is a new joint. Each of these lines starts with a string inside two quotation marks, which is the name of the joint. Following the name of the joint is the parent index. A parent index of "-1" means that this joint is at the top of the hierarchy, and has no parent. The next number is a flag which describes which parts of the joint (position and orientation's x, y and z) will be updated in the frames section later. The last value, is the start index. The start index is the value in the frame data to start updating this specific joint. As you can see in the peice of code below, the "bip01"'s start index is "0", which means that it will be updated starting with the very first value in the frame data. The flags section will define how to update the joint, and how many values from the start index to use in the frame data (between 1 and 6, because 3 for position and 3 for orientation).


joints {
	"Bip01"	-1 63 0
    ...
}


"bounds"

These are the bounds, or an axis aligned bounding box for each of the frames. Each line after "bounds" is a frames AABB, which consists of a min and max point describing the largest and smallest value on each of the x y and z axes. The first three floats inside the paranthesis describe the min point, while the next three describe the max point.


( -30.4137325286 -23.4689254760 -42.4965248107 ) ( 35.7306137084 6.3094730377 48.7827911376 )


"baseframe"

This is the default position of each joint in the animation. This is not necessarily the same as the bind-pose described in the .md5mesh. Each frame will build it's frame skeleton from this baseframe, since not every frame describes every joints position and rotation. Because of this, it is possible that the baseframe is filled with some or even all zeros, in the case that some or all of the joints positions or orientations are updated every frame.

Each line after "baseframe" describes the corresponding joints position and orientation, where the first three values in the line are the position, and the last three are the orientation.


( 0.5196304321 1.7362534999 4.6482505798 ) ( 0.0000000000 0.0000000000 0.7071063041 )


"frame"

The last section to talk about in the .md5anim file, is the frames section. Each frame of animation will have their own section, and in each section, is a list of floats. The number of floats is defined by "numAnimatedComponents" in the header. Each float will replace one of the x, y, or z values of the position or orientaion of the baseframes joint. Which value and which component of the joint (x, y, or z of the position or rientation) is decided by the joints flag and start index.


0.5196304321 1.7362534999 4.6482505798 0.0000000000 0.0000000000 0.7071063041


Animating the Normals

Computing the normals for every vertex can be pretty slow sometimes, so we have a way around this for when we animate our model, so we don't have to compute the normals for every frame. The way we do this is by computing the normals in joint space (for each weight) when we load in the original model from the .md5mesh file (we have updated the function to do this in this lesson). After we have the normals in joint space, we can easily rotate the normals for each frame depending on the joints orientation, the exact same way we rotate the weights position using the joints orientation, except that we don't even have to reposition the normal.

When computing the normal in joint space, we first compute the normals for each vertex like we normaly would for the model. We can then use these vertex normals and rotate them by the inverse of the joints orientation. We will go through each of the weights for this vertex and do this computation with the joint that each of these weights is bound to.


Right/Left Handed Coordinat Systems

You will probably notice that I have swapped the "z" and "y" values when loading in the .md5mesh and .md5anim. This is because the file was exported from a Right handed coordinate system, while directx uses a left handed coordinated system. If your model happnes to be in a left handed coordinate system already, you can just re-swap the y and z values when loading in the data.



New Structures

We have a couple new structures here. The first you can see is for the bounding box, loaded from the bounds section in the md5anim file. The next structure that you can see is the frame data structure. This structure will contain a number identifying which frame, and an array of floats, which is the frame data. These floats will then be used to update the baseframe skeleton for each frame.

Next we have a new structure for our joints. This structure holds different data than the other joint structure, since the joints for each animation (since md5mesh files can contain one or more md5anim files) can differ from animation to animation. So this structure holds animation specific data, like the flags (which components of the joint should be updated per frame) and the startindex (the first value in the frame data array to start updating with).

Next is our ModelAnimation structure. You will see next that we have a vector of these as a member or our Model3D structure. This is because each model might contain one or more animations. Anyway, this structure holds information about the animation, along with the animation itself (skeleton poses for each frame). The members have been explained above or are easy enough to understand without my explanation. But I will explain the last member, the frameSkeleton. Each skeleton is defined by a vector of joints, and in the animation, each frame has a single skeleton. So you can see that we have the first vector for each frame of animation, and the vector within that one is a vector of the joints of the skeleton. We can then later call a single joint from this member something like this "frameSkeleton[frame][joint]", or simply an entire frame skeleton like this "frameSkeleton[frame]".


struct BoundingBox
{
	XMFLOAT3 min;
	XMFLOAT3 max;
};

struct FrameData
{
	int frameID;
	std::vector<float> frameData;
};
struct AnimJointInfo
{
	std::wstring name;
	int parentID;

	int flags;
	int startIndex;
};

struct ModelAnimation
{
	int numFrames;
	int numJoints;
	int frameRate;
	int numAnimatedComponents;

	float frameTime;
	float totalAnimTime;
	float currAnimTime;

	std::vector<AnimJointInfo> jointInfo;
	std::vector<BoundingBox> frameBounds;
	std::vector<Joint>	baseFrameJoints;
	std::vector<FrameData>	frameData;
	std::vector<std::vector<Joint>> frameSkeleton;
};

Updated Weight Structure

We have updated our weight structure to include a normal. This is because if we define the normal in joint space, we can easily change it as our animation progresses, instead of having to recompute every single normal for every frame.


struct Weight
{
	int jointID;
	float bias;
	XMFLOAT3 pos;
	///////////////**************new**************////////////////////
	XMFLOAT3 normal;
	///////////////**************new**************////////////////////
};

Updated Model3D Structure

Here you can see we have updated the Model3D structure to hold an array of animations.


struct Model3D
{
	int numSubsets;
	int numJoints;

	std::vector<Joint> joints;
	std::vector<ModelSubset> subsets;

	///////////////**************new**************////////////////////
	std::vector<ModelAnimation> animations;
	///////////////**************new**************////////////////////
};

Two New Functions

These are our new functions. The first one loads the animation from the .md5anim file, and the second one update the vertex buffer based on the time passed in the animation, and which animation to even use.

bool LoadMD5Anim(std::wstring filename,	Model3D& MD5Model);

void UpdateMD5Model(Model3D& MD5Model, float deltaTime, int animation);

The DetectInput() Function

There is a new key detection here. That key is letter "R". When we press this key, our animation will update. I have added a float called "timeFactor" which you can use to speed up or slow down time, or at least time in the animation scope. If you are really speeding up time or slowing it down throughout the game, you will need to put this time facter in a larger scope.


void DetectInput(double time)
{
	DIMOUSESTATE mouseCurrState;

	BYTE keyboardState[256];

	DIKeyboard->Acquire();
	DIMouse->Acquire();

	DIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseCurrState);

	DIKeyboard->GetDeviceState(sizeof(keyboardState),(LPVOID)&keyboardState);

	if(keyboardState[DIK_ESCAPE] & 0x80)
		PostMessage(hwnd, WM_DESTROY, 0, 0);

	float speed = 10.0f * time;

	if(keyboardState[DIK_A] & 0x80)
	{
		moveLeftRight -= speed;
	}
	if(keyboardState[DIK_D] & 0x80)
	{
		moveLeftRight += speed;
	}
	if(keyboardState[DIK_W] & 0x80)
	{
		moveBackForward += speed;
	}
	if(keyboardState[DIK_S] & 0x80)
	{
		moveBackForward -= speed;
	}
	///////////////**************new**************////////////////////
	if(keyboardState[DIK_R] & 0X80)
	{
		float timeFactor = 1.0f;	// You can speed up or slow down time by changing this
		UpdateMD5Model(NewMD5Model, time*timeFactor, 0);
	}
	///////////////**************new**************////////////////////
	if((mouseCurrState.lX != mouseLastState.lX) || (mouseCurrState.lY != mouseLastState.lY))
	{
		camYaw += mouseLastState.lX * 0.001f;

		camPitch += mouseCurrState.lY * 0.001f;

		mouseLastState = mouseCurrState;
	}

	UpdateCamera();

	return;
}

The LoadMD5Anim() Function

Here we will load the animation. This file will also create the skeletons for every frame of animation. I will go through this function chunk by chunk.


bool LoadMD5Anim(std::wstring filename,	Model3D& MD5Model)
{	
	ModelAnimation tempAnim;						// Temp animation to later store in our model's animation array

	std::wifstream fileIn (filename.c_str());		// Open file

	std::wstring checkString;						// Stores the next string from our file

	if(fileIn)										// Check if the file was opened
	{
		while(fileIn)								// Loop until the end of the file is reached
		{	
			fileIn >> checkString;					// Get next string from file

			if ( checkString == L"MD5Version" )		// Get MD5 version (this function supports version 10)
			{
				fileIn >> checkString;
				/*MessageBox(0, checkString.c_str(),	//display message
				L"MD5Version", MB_OK);*/
			}
			else if ( checkString == L"commandline" )
			{
				std::getline(fileIn, checkString);	// Ignore the rest of this line
			}
			else if ( checkString == L"numFrames" )
			{
				fileIn >> tempAnim.numFrames;				// Store number of frames in this animation
			}
			else if ( checkString == L"numJoints" )
			{
				fileIn >> tempAnim.numJoints;				// Store number of joints (must match .md5mesh)
			}
			else if ( checkString == L"frameRate" )
			{
				fileIn >> tempAnim.frameRate;				// Store animation's frame rate (frames per second)
			}
			else if ( checkString == L"numAnimatedComponents" )
			{
				fileIn >> tempAnim.numAnimatedComponents;	// Number of components in each frame section
			}
			else if ( checkString == L"hierarchy" )
			{
				fileIn >> checkString;				// Skip opening bracket "{"

				for(int i = 0; i < tempAnim.numJoints; i++)	// Load in each joint
				{
					AnimJointInfo tempJoint;

					fileIn >> tempJoint.name;		// Get joints name
					// Sometimes the names might contain spaces. If that is the case, we need to continue
					// to read the name until we get to the closing " (quotation marks)
					if(tempJoint.name[tempJoint.name.size()-1] != '"')
					{
						wchar_t checkChar;
						bool jointNameFound = false;
						while(!jointNameFound)
						{
							checkChar = fileIn.get();

							if(checkChar == '"')
								jointNameFound = true;		

							tempJoint.name += checkChar;															
						}
					}

					// Remove the quotation marks from joints name
					tempJoint.name.erase(0, 1);
					tempJoint.name.erase(tempJoint.name.size()-1, 1);

					fileIn >> tempJoint.parentID;			// Get joints parent ID
					fileIn >> tempJoint.flags;				// Get flags
					fileIn >> tempJoint.startIndex;			// Get joints start index

					// Make sure the joint exists in the model, and the parent ID's match up
					// because the bind pose (md5mesh) joint hierarchy and the animations (md5anim)
					// joint hierarchy must match up
					bool jointMatchFound = false;
					for(int k = 0; k < MD5Model.numJoints; k++)
					{
						if(MD5Model.joints[k].name == tempJoint.name)
						{
							if(MD5Model.joints[k].parentID == tempJoint.parentID)
							{
								jointMatchFound = true;
								tempAnim.jointInfo.push_back(tempJoint);
							}
						}
					}
					if(!jointMatchFound)					// If the skeleton system does not match up, return false
						return false;						// You might want to add an error message here

					std::getline(fileIn, checkString);		// Skip rest of this line
				}
			}
			else if ( checkString == L"bounds" )			// Load in the AABB for each animation
			{
				fileIn >> checkString;						// Skip opening bracket "{"

				for(int i = 0; i < tempAnim.numFrames; i++)
				{
					BoundingBox tempBB;

					fileIn >> checkString;					// Skip "("
					fileIn >> tempBB.min.x >> tempBB.min.z >> tempBB.min.y;
					fileIn >> checkString >> checkString;	// Skip ") ("
					fileIn >> tempBB.max.x >> tempBB.max.z >> tempBB.max.y;
					fileIn >> checkString;					// Skip ")"

					tempAnim.frameBounds.push_back(tempBB);
				}
			}			
			else if ( checkString == L"baseframe" )			// This is the default position for the animation
			{												// All frames will build their skeletons off this
				fileIn >> checkString;						// Skip opening bracket "{"

				for(int i = 0; i < tempAnim.numJoints; i++)
				{
					Joint tempBFJ;

					fileIn >> checkString;						// Skip "("
					fileIn >> tempBFJ.pos.x >> tempBFJ.pos.z >> tempBFJ.pos.y;
					fileIn >> checkString >> checkString;		// Skip ") ("
					fileIn >> tempBFJ.orientation.x >> tempBFJ.orientation.z >> tempBFJ.orientation.y;
					fileIn >> checkString;						// Skip ")"

					tempAnim.baseFrameJoints.push_back(tempBFJ);
				}
			}
			else if ( checkString == L"frame" )		// Load in each frames skeleton (the parts of each joint that changed from the base frame)
			{
				FrameData tempFrame;

				fileIn >> tempFrame.frameID;		// Get the frame ID

				fileIn >> checkString;				// Skip opening bracket "{"

				for(int i = 0; i < tempAnim.numAnimatedComponents; i++)
				{
					float tempData;
					fileIn >> tempData;				// Get the data

					tempFrame.frameData.push_back(tempData);
				}

				tempAnim.frameData.push_back(tempFrame);

				///*** build the frame skeleton ***///
				std::vector tempSkeleton;

				for(int i = 0; i < tempAnim.jointInfo.size(); i++)
				{
					int k = 0;						// Keep track of position in frameData array

					// Start the frames joint with the base frame's joint
					Joint tempFrameJoint = tempAnim.baseFrameJoints[i];

					tempFrameJoint.parentID = tempAnim.jointInfo[i].parentID;

					// Notice how I have been flipping y and z. this is because some modeling programs such as
					// 3ds max (which is what I use) use a right handed coordinate system. Because of this, we
					// need to flip the y and z axes. If your having problems loading some models, it's possible
					// the model was created in a left hand coordinate system. in that case, just reflip all the
					// y and z axes in our md5 mesh and anim loader.
					if(tempAnim.jointInfo[i].flags & 1)		// pos.x	( 000001 )
						tempFrameJoint.pos.x = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];

					if(tempAnim.jointInfo[i].flags & 2)		// pos.y	( 000010 )
						tempFrameJoint.pos.z = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];

					if(tempAnim.jointInfo[i].flags & 4)		// pos.z	( 000100 )
						tempFrameJoint.pos.y = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];

					if(tempAnim.jointInfo[i].flags & 8)		// orientation.x	( 001000 )
						tempFrameJoint.orientation.x = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];

					if(tempAnim.jointInfo[i].flags & 16)	// orientation.y	( 010000 )
						tempFrameJoint.orientation.z = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];

					if(tempAnim.jointInfo[i].flags & 32)	// orientation.z	( 100000 )
						tempFrameJoint.orientation.y = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];


					// Compute the quaternions w
					float t = 1.0f - ( tempFrameJoint.orientation.x * tempFrameJoint.orientation.x )
						- ( tempFrameJoint.orientation.y * tempFrameJoint.orientation.y )
						- ( tempFrameJoint.orientation.z * tempFrameJoint.orientation.z );
					if ( t < 0.0f )
					{
						tempFrameJoint.orientation.w = 0.0f;
					}
					else
					{
						tempFrameJoint.orientation.w = -sqrtf(t);
					}

					// Now, if the upper arm of your skeleton moves, you need to also move the lower part of your arm, and then the hands, and then finally the fingers (possibly weapon or tool too)
					// This is where joint hierarchy comes in. We start at the top of the hierarchy, and move down to each joints child, rotating and translating them based on their parents rotation
					// and translation. We can assume that by the time we get to the child, the parent has already been rotated and transformed based of it's parent. We can assume this because
					// the child should never come before the parent in the files we loaded in.
					if(tempFrameJoint.parentID >= 0)
					{
						Joint parentJoint = tempSkeleton[tempFrameJoint.parentID];

						// Turn the XMFLOAT3 and 4's into vectors for easier computation
						XMVECTOR parentJointOrientation = XMVectorSet(parentJoint.orientation.x, parentJoint.orientation.y, parentJoint.orientation.z, parentJoint.orientation.w);
						XMVECTOR tempJointPos = XMVectorSet(tempFrameJoint.pos.x, tempFrameJoint.pos.y, tempFrameJoint.pos.z, 0.0f);
						XMVECTOR parentOrientationConjugate = XMVectorSet(-parentJoint.orientation.x, -parentJoint.orientation.y, -parentJoint.orientation.z, parentJoint.orientation.w);

						// Calculate current joints position relative to its parents position
						XMFLOAT3 rotatedPos;
						XMStoreFloat3(&rotatedPos, XMQuaternionMultiply(XMQuaternionMultiply(parentJointOrientation, tempJointPos), parentOrientationConjugate));

						// Translate the joint to model space by adding the parent joint's pos to it
						tempFrameJoint.pos.x = rotatedPos.x + parentJoint.pos.x;
						tempFrameJoint.pos.y = rotatedPos.y + parentJoint.pos.y;
						tempFrameJoint.pos.z = rotatedPos.z + parentJoint.pos.z;

						// Currently the joint is oriented in its parent joints space, we now need to orient it in
						// model space by multiplying the two orientations together (parentOrientation * childOrientation) <- In that order
						XMVECTOR tempJointOrient = XMVectorSet(tempFrameJoint.orientation.x, tempFrameJoint.orientation.y, tempFrameJoint.orientation.z, tempFrameJoint.orientation.w);
						tempJointOrient = XMQuaternionMultiply(parentJointOrientation, tempJointOrient);

						// Normalize the orienation quaternion
						tempJointOrient = XMQuaternionNormalize(tempJointOrient);

						XMStoreFloat4(&tempFrameJoint.orientation, tempJointOrient);
					}

					// Store the joint into our temporary frame skeleton
					tempSkeleton.push_back(tempFrameJoint);
				}

				// Push back our newly created frame skeleton into the animation's frameSkeleton array
				tempAnim.frameSkeleton.push_back(tempSkeleton);

				fileIn >> checkString;				// Skip closing bracket "}"
			}
		}

		// Calculate and store some usefull animation data
		tempAnim.frameTime = 1.0f / tempAnim.frameRate;						// Set the time per frame
		tempAnim.totalAnimTime = tempAnim.numFrames * tempAnim.frameTime;	// Set the total time the animation takes
		tempAnim.currAnimTime = 0.0f;										// Set the current time to zero

		MD5Model.animations.push_back(tempAnim);							// Push back the animation into our model object
	}
	else	// If the file was not loaded
	{
		SwapChain->SetFullscreenState(false, NULL);	// Make sure we are out of fullscreen

		// create message
		std::wstring message = L"Could not open: ";
		message += filename;

		MessageBox(0, message.c_str(),				// display message
			L"Error", MB_OK);

		return false;
	}
	return true;
}

Opening the File and Reading the Header Info

I don't want to spend too much time explaining things that have been explained in earlier lessons, so if you have at least read the last lesson you will know whats happening here.


bool LoadMD5Anim(std::wstring filename,	Model3D& MD5Model)
{	
	ModelAnimation tempAnim;						// Temp animation to later store in our model's animation array

	std::wifstream fileIn (filename.c_str());		// Open file

	std::wstring checkString;						// Stores the next string from our file

	if(fileIn)										// Check if the file was opened
	{
		while(fileIn)								// Loop until the end of the file is reached
		{	
			fileIn >> checkString;					// Get next string from file

			if ( checkString == L"MD5Version" )		// Get MD5 version (this function supports version 10)
			{
				fileIn >> checkString;
				/*MessageBox(0, checkString.c_str(),	//display message
				L"MD5Version", MB_OK);*/
			}
			else if ( checkString == L"commandline" )
			{
				std::getline(fileIn, checkString);	// Ignore the rest of this line
			}
			else if ( checkString == L"numFrames" )
			{
				fileIn >> tempAnim.numFrames;				// Store number of frames in this animation
			}
			else if ( checkString == L"numJoints" )
			{
				fileIn >> tempAnim.numJoints;				// Store number of joints (must match .md5mesh)
			}
			else if ( checkString == L"frameRate" )
			{
				fileIn >> tempAnim.frameRate;				// Store animation's frame rate (frames per second)
			}
			else if ( checkString == L"numAnimatedComponents" )
			{
				fileIn >> tempAnim.numAnimatedComponents;	// Number of components in each frame section
			}
			
            ...
	}
	else	// If the file was not loaded
	{
		SwapChain->SetFullscreenState(false, NULL);	// Make sure we are out of fullscreen

		// create message
		std::wstring message = L"Could not open: ";
		message += filename;

		MessageBox(0, message.c_str(),				// display message
			L"Error", MB_OK);

		return false;
	}
	return true;
}

Load the Joint Hierarchy

Next we load in the joint hierarchy. Like we mentioned above, we check to make sure this hierarchy matches up with the one from the .md5mesh file. If not, we return false.


			else if ( checkString == L"hierarchy" )
			{
				fileIn >> checkString;				// Skip opening bracket "{"

				for(int i = 0; i < tempAnim.numJoints; i++)	// Load in each joint
				{
					AnimJointInfo tempJoint;

					fileIn >> tempJoint.name;		// Get joints name
					// Sometimes the names might contain spaces. If that is the case, we need to continue
					// to read the name until we get to the closing " (quotation marks)
					if(tempJoint.name[tempJoint.name.size()-1] != '"')
					{
						wchar_t checkChar;
						bool jointNameFound = false;
						while(!jointNameFound)
						{
							checkChar = fileIn.get();

							if(checkChar == '"')
								jointNameFound = true;		

							tempJoint.name += checkChar;															
						}
					}

					// Remove the quotation marks from joints name
					tempJoint.name.erase(0, 1);
					tempJoint.name.erase(tempJoint.name.size()-1, 1);

					fileIn >> tempJoint.parentID;			// Get joints parent ID
					fileIn >> tempJoint.flags;				// Get flags
					fileIn >> tempJoint.startIndex;			// Get joints start index

					// Make sure the joint exists in the model, and the parent ID's match up
					// because the bind pose (md5mesh) joint hierarchy and the animations (md5anim)
					// joint hierarchy must match up
					bool jointMatchFound = false;
					for(int k = 0; k < MD5Model.numJoints; k++)
					{
						if(MD5Model.joints[k].name == tempJoint.name)
						{
							if(MD5Model.joints[k].parentID == tempJoint.parentID)
							{
								jointMatchFound = true;
								tempAnim.jointInfo.push_back(tempJoint);
							}
						}
					}
					if(!jointMatchFound)					// If the skeleton system does not match up, return false
						return false;						// You might want to add an error message here

					std::getline(fileIn, checkString);		// Skip rest of this line
				}
			}

Load Each Frames Bounding Box (AABB)

Now we load in each frames bounding box, or the min and max points. We will not use the bounding boxes in this lesson, but they can be used for any purpose you see fit, like collision detection is what comes first to my mind.


			else if ( checkString == L"bounds" )			// Load in the AABB for each animation
			{
				fileIn >> checkString;						// Skip opening bracket "{"

				for(int i = 0; i < tempAnim.numFrames; i++)
				{
					BoundingBox tempBB;

					fileIn >> checkString;					// Skip "("
					fileIn >> tempBB.min.x >> tempBB.min.z >> tempBB.min.y;
					fileIn >> checkString >> checkString;	// Skip ") ("
					fileIn >> tempBB.max.x >> tempBB.max.z >> tempBB.max.y;
					fileIn >> checkString;					// Skip ")"

					tempAnim.frameBounds.push_back(tempBB);
				}
			}			

Loading the Baseframe

Here we load in the baseframe, again, not much to say about it other than its the skeleton that all the frame skeletons build off of.


			else if ( checkString == L"baseframe" )			// This is the default position for the animation
			{												// All frames will build their skeletons off this
				fileIn >> checkString;						// Skip opening bracket "{"

				for(int i = 0; i < tempAnim.numJoints; i++)
				{
					Joint tempBFJ;

					fileIn >> checkString;						// Skip "("
					fileIn >> tempBFJ.pos.x >> tempBFJ.pos.z >> tempBFJ.pos.y;
					fileIn >> checkString >> checkString;		// Skip ") ("
					fileIn >> tempBFJ.orientation.x >> tempBFJ.orientation.z >> tempBFJ.orientation.y;
					fileIn >> checkString;						// Skip ")"

					tempAnim.baseFrameJoints.push_back(tempBFJ);
				}
			}

Loading the Frame

Here we get to the frame sections. The frame sections contain an array of float values (the number is described by numAnimatedComponents in the header).


			else if ( checkString == L"frame" )		// Load in each frames skeleton (the parts of each joint that changed from the base frame)
			{
				FrameData tempFrame;

				fileIn >> tempFrame.frameID;		// Get the frame ID

				fileIn >> checkString;				// Skip opening bracket "{"

				for(int i = 0; i < tempAnim.numAnimatedComponents; i++)
				{
					float tempData;
					fileIn >> tempData;				// Get the data

					tempFrame.frameData.push_back(tempData);
				}

				tempAnim.frameData.push_back(tempFrame);

Creating the Frame Skeleton

Now that we have just loaded a frame containing a bunch of floats for data, we can create a frame skeleton for this frame, using that data we just got. This is where the joints "flag" comes in, along with it's start index. I'll start by explaining the flag.

The flag is a bitwise number (0's and 1's), or more specifically, a 64-bit number, that says which part of a joint should be updated. It goes in order from the first bit being the joints position x value should be updated, to the last being the joints orientation z value. For example, "1" or (000001), says that the joints positions x should be replaced by the float in the frame data array. "7" or (000111) says that all x, y, and z of the joints position should be updated with the next three values in the frame data. "63" or (111111) says that both the positin and orientations x y and z values should be updated.

The start index of the joint says where to start in the frame data array, or the starting value to use to update the joint. We check each of the six possible flags for the joint, and if one is set, we replace the x, y, or z of the position or orientation, then increment the "k", which is keeping track of our position in the frame data array from the start index of the joint.

If you can understand this, you will realize it's not so difficult, I just can't seem to explain it without being so "wordy".

After we update the joints of the frame skeleton from the baseframe, we calculate the "w" value of the orientation quaternion before updating the frames joints based on their parents position and orientation.


				///*** build the frame skeleton ***///
				std::vector<Joint> tempSkeleton;

				for(int i = 0; i < tempAnim.jointInfo.size(); i++)
				{
					int k = 0;						// Keep track of position in frameData array

					// Start the frames joint with the base frame's joint
					Joint tempFrameJoint = tempAnim.baseFrameJoints[i];

					tempFrameJoint.parentID = tempAnim.jointInfo[i].parentID;

					// Notice how I have been flipping y and z. this is because some modeling programs such as
					// 3ds max (which is what I use) use a right handed coordinate system. Because of this, we
					// need to flip the y and z axes. If your having problems loading some models, it's possible
					// the model was created in a left hand coordinate system. in that case, just reflip all the
					// y and z axes in our md5 mesh and anim loader.
					if(tempAnim.jointInfo[i].flags & 1)		// pos.x	( 000001 )
						tempFrameJoint.pos.x = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];

					if(tempAnim.jointInfo[i].flags & 2)		// pos.y	( 000010 )
						tempFrameJoint.pos.z = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];

					if(tempAnim.jointInfo[i].flags & 4)		// pos.z	( 000100 )
						tempFrameJoint.pos.y = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];

					if(tempAnim.jointInfo[i].flags & 8)		// orientation.x	( 001000 )
						tempFrameJoint.orientation.x = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];

					if(tempAnim.jointInfo[i].flags & 16)	// orientation.y	( 010000 )
						tempFrameJoint.orientation.z = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];

					if(tempAnim.jointInfo[i].flags & 32)	// orientation.z	( 100000 )
						tempFrameJoint.orientation.y = tempFrame.frameData[tempAnim.jointInfo[i].startIndex + k++];


					// Compute the quaternions w
					float t = 1.0f - ( tempFrameJoint.orientation.x * tempFrameJoint.orientation.x )
						- ( tempFrameJoint.orientation.y * tempFrameJoint.orientation.y )
						- ( tempFrameJoint.orientation.z * tempFrameJoint.orientation.z );
					if ( t < 0.0f )
					{
						tempFrameJoint.orientation.w = 0.0f;
					}
					else
					{
						tempFrameJoint.orientation.w = -sqrtf(t);
					}

Update Frame Skeleton Joints Based On Parent's Position and Orientation

Next we do what was just said above, updating the joints based on the parent. We can assume that a child never comes before the parent in the hierarchy list, so we know that a child will not be processed before its parent, since, if that were the case it would be pointless to do what we are about to do. We go through each joint, and find its parent joint (as long as it has a parent, since the top joint doesn't have one). We then rotate the joint's position based on the parents orientation. Then we need to add the parents position to the childs position to put it into model space. After that we need to reorient the child joint based on the parent joint. To do that, we simply multiply them together (parent * child).


					// Now, if the upper arm of your skeleton moves, you need to also move the lower part of your arm, and then the hands, and then finally the fingers (possibly weapon or tool too)
					// This is where joint hierarchy comes in. We start at the top of the hierarchy, and move down to each joints child, rotating and translating them based on their parents rotation
					// and translation. We can assume that by the time we get to the child, the parent has already been rotated and transformed based of it's parent. We can assume this because
					// the child should never come before the parent in the files we loaded in.
					if(tempFrameJoint.parentID >= 0)
					{
						Joint parentJoint = tempSkeleton[tempFrameJoint.parentID];

						// Turn the XMFLOAT3 and 4's into vectors for easier computation
						XMVECTOR parentJointOrientation = XMVectorSet(parentJoint.orientation.x, parentJoint.orientation.y, parentJoint.orientation.z, parentJoint.orientation.w);
						XMVECTOR tempJointPos = XMVectorSet(tempFrameJoint.pos.x, tempFrameJoint.pos.y, tempFrameJoint.pos.z, 0.0f);
						XMVECTOR parentOrientationConjugate = XMVectorSet(-parentJoint.orientation.x, -parentJoint.orientation.y, -parentJoint.orientation.z, parentJoint.orientation.w);

						// Calculate current joints position relative to its parents position
						XMFLOAT3 rotatedPos;
						XMStoreFloat3(&rotatedPos, XMQuaternionMultiply(XMQuaternionMultiply(parentJointOrientation, tempJointPos), parentOrientationConjugate));

						// Translate the joint to model space by adding the parent joint's pos to it
						tempFrameJoint.pos.x = rotatedPos.x + parentJoint.pos.x;
						tempFrameJoint.pos.y = rotatedPos.y + parentJoint.pos.y;
						tempFrameJoint.pos.z = rotatedPos.z + parentJoint.pos.z;

						// Currently the joint is oriented in its parent joints space, we now need to orient it in
						// model space by multiplying the two orientations together (parentOrientation * childOrientation) <- In that order
						XMVECTOR tempJointOrient = XMVectorSet(tempFrameJoint.orientation.x, tempFrameJoint.orientation.y, tempFrameJoint.orientation.z, tempFrameJoint.orientation.w);
						tempJointOrient = XMQuaternionMultiply(parentJointOrientation, tempJointOrient);

						// Normalize the orienation quaternion
						tempJointOrient = XMQuaternionNormalize(tempJointOrient);

						XMStoreFloat4(&tempFrameJoint.orientation, tempJointOrient);
					}

					// Store the joint into our temporary frame skeleton
					tempSkeleton.push_back(tempFrameJoint);
				}

				// Push back our newly created frame skeleton into the animation's frameSkeleton array
				tempAnim.frameSkeleton.push_back(tempSkeleton);

				fileIn >> checkString;				// Skip closing bracket "}"
			}
		}

Calculating Some Frame Stuff

We will need to know the length in time of each frame, and the total animation time, so we calculate those quick. We also make sure that the current animation time is set to zero. After we do all that, we push back the temp animation to our models animation vector, and exit the function successfully.


		// Calculate and store some usefull animation data
		tempAnim.frameTime = 1.0f / tempAnim.frameRate;						// Set the time per frame
		tempAnim.totalAnimTime = tempAnim.numFrames * tempAnim.frameTime;	// Set the total time the animation takes
		tempAnim.currAnimTime = 0.0f;										// Set the current time to zero

		MD5Model.animations.push_back(tempAnim);							// Push back the animation into our model object

The UpdateMD5Model() Function

Here's the function that we will call whenever we want to update our model using the animation. I'll go through this function in chunks too.


void UpdateMD5Model(Model3D& MD5Model, float deltaTime, int animation)
{
	MD5Model.animations[animation].currAnimTime += deltaTime;			// Update the current animation time

	if(MD5Model.animations[animation].currAnimTime > MD5Model.animations[animation].totalAnimTime)
		MD5Model.animations[animation].currAnimTime = 0.0f;

	// Which frame are we on
	float currentFrame = MD5Model.animations[animation].currAnimTime * MD5Model.animations[animation].frameRate;	
	int frame0 = floorf( currentFrame );
	int frame1 = frame0 + 1;

	// Make sure we don't go over the number of frames	
	if(frame0 == MD5Model.animations[animation].numFrames-1)
		frame1 = 0;

	float interpolation = currentFrame - frame0;	// Get the remainder (in time) between frame0 and frame1 to use as interpolation factor

	std::vector<Joint> interpolatedSkeleton;		// Create a frame skeleton to store the interpolated skeletons in

	// Compute the interpolated skeleton
	for( int i = 0; i < MD5Model.animations[animation].numJoints; i++)
	{
		Joint tempJoint;
		Joint joint0 = MD5Model.animations[animation].frameSkeleton[frame0][i];		// Get the i'th joint of frame0's skeleton
		Joint joint1 = MD5Model.animations[animation].frameSkeleton[frame1][i];		// Get the i'th joint of frame1's skeleton

		tempJoint.parentID = joint0.parentID;											// Set the tempJoints parent id

		// Turn the two quaternions into XMVECTORs for easy computations
		XMVECTOR joint0Orient = XMVectorSet(joint0.orientation.x, joint0.orientation.y, joint0.orientation.z, joint0.orientation.w);
		XMVECTOR joint1Orient = XMVectorSet(joint1.orientation.x, joint1.orientation.y, joint1.orientation.z, joint1.orientation.w);

		// Interpolate positions
		tempJoint.pos.x = joint0.pos.x + (interpolation * (joint1.pos.x - joint0.pos.x));
		tempJoint.pos.y = joint0.pos.y + (interpolation * (joint1.pos.y - joint0.pos.y));
		tempJoint.pos.z = joint0.pos.z + (interpolation * (joint1.pos.z - joint0.pos.z));

		// Interpolate orientations using spherical interpolation (Slerp)
		XMStoreFloat4(&tempJoint.orientation, XMQuaternionSlerp(joint0Orient, joint1Orient, interpolation));

		interpolatedSkeleton.push_back(tempJoint);		// Push the joint back into our interpolated skeleton
	}

	for ( int k = 0; k < MD5Model.numSubsets; k++)
	{
		for ( int i = 0; i < MD5Model.subsets[k].vertices.size(); ++i )
		{
			Vertex tempVert = MD5Model.subsets[k].vertices[i];
			tempVert.pos = XMFLOAT3(0, 0, 0);	// Make sure the vertex's pos is cleared first
			tempVert.normal = XMFLOAT3(0,0,0);	// Clear vertices normal

			// Sum up the joints and weights information to get vertex's position and normal
			for ( int j = 0; j < tempVert.WeightCount; ++j )
			{
				Weight tempWeight = MD5Model.subsets[k].weights[tempVert.StartWeight + j];
				Joint tempJoint = interpolatedSkeleton[tempWeight.jointID];

				// Convert joint orientation and weight pos to vectors for easier computation
				XMVECTOR tempJointOrientation = XMVectorSet(tempJoint.orientation.x, tempJoint.orientation.y, tempJoint.orientation.z, tempJoint.orientation.w);
				XMVECTOR tempWeightPos = XMVectorSet(tempWeight.pos.x, tempWeight.pos.y, tempWeight.pos.z, 0.0f);

				// We will need to use the conjugate of the joint orientation quaternion
				XMVECTOR tempJointOrientationConjugate = XMQuaternionInverse(tempJointOrientation);

				// Calculate vertex position (in joint space, eg. rotate the point around (0,0,0)) for this weight using the joint orientation quaternion and its conjugate
				// We can rotate a point using a quaternion with the equation "rotatedPoint = quaternion * point * quaternionConjugate"
				XMFLOAT3 rotatedPoint;
				XMStoreFloat3(&rotatedPoint, XMQuaternionMultiply(XMQuaternionMultiply(tempJointOrientation, tempWeightPos), tempJointOrientationConjugate));

				// Now move the verices position from joint space (0,0,0) to the joints position in world space, taking the weights bias into account
				tempVert.pos.x += ( tempJoint.pos.x + rotatedPoint.x ) * tempWeight.bias;
				tempVert.pos.y += ( tempJoint.pos.y + rotatedPoint.y ) * tempWeight.bias;
				tempVert.pos.z += ( tempJoint.pos.z + rotatedPoint.z ) * tempWeight.bias;

				// Compute the normals for this frames skeleton using the weight normals from before
				// We can comput the normals the same way we compute the vertices position, only we don't have to translate them (just rotate)
				XMVECTOR tempWeightNormal = XMVectorSet(tempWeight.normal.x, tempWeight.normal.y, tempWeight.normal.z, 0.0f);

				// Rotate the normal
				XMStoreFloat3(&rotatedPoint, XMQuaternionMultiply(XMQuaternionMultiply(tempJointOrientation, tempWeightNormal), tempJointOrientationConjugate));

				// Add to vertices normal and ake weight bias into account
				tempVert.normal.x -= rotatedPoint.x * tempWeight.bias;
				tempVert.normal.y -= rotatedPoint.y * tempWeight.bias;
				tempVert.normal.z -= rotatedPoint.z * tempWeight.bias;
			}

			MD5Model.subsets[k].positions[i] = tempVert.pos;				// Store the vertices position in the position vector instead of straight into the vertex vector
			MD5Model.subsets[k].vertices[i].normal = tempVert.normal;		// Store the vertices normal
			XMStoreFloat3(&MD5Model.subsets[k].vertices[i].normal, XMVector3Normalize(XMLoadFloat3(&MD5Model.subsets[k].vertices[i].normal)));
		}

		// Put the positions into the vertices for this subset
		for(int i = 0; i < MD5Model.subsets[k].vertices.size(); i++)
		{
			MD5Model.subsets[k].vertices[i].pos = MD5Model.subsets[k].positions[i];
		}

		// Update the subsets vertex buffer
		// First lock the buffer
		D3D11_MAPPED_SUBRESOURCE mappedVertBuff;
		hr = d3d11DevCon->Map(MD5Model.subsets[k].vertBuff, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedVertBuff);

		// Copy the data into the vertex buffer.
		memcpy(mappedVertBuff.pData, &MD5Model.subsets[k].vertices[0], (sizeof(Vertex) * MD5Model.subsets[k].vertices.size()));

		d3d11DevCon->Unmap(MD5Model.subsets[k].vertBuff, 0);

		// The line below is another way to update a buffer. You will use this when you want to update a buffer less
		// than once per frame, since the GPU reads will be faster (the buffer was created as a DEFAULT buffer instead
		// of a DYNAMIC buffer), and the CPU writes will be slower. You can try both methods to find out which one is faster
		// for you. if you want to use the line below, you will have to create the buffer with D3D11_USAGE_DEFAULT instead
		// of D3D11_USAGE_DYNAMIC
		//d3d11DevCon->UpdateSubresource( MD5Model.subsets[k].vertBuff, 0, NULL, &MD5Model.subsets[k].vertices[0], 0, 0 );
	}
}

Which Frames to Use

We start the function by updating the animations current time. If the current animation time is over the total animation time, we reset the current animation time to zero to restart the animation. After that we find out which frames we are on. We can do this by multiplying the current animation time by the frameRate. Rounding this answer down to the nearest whole number gives us the frame we are currently on, and adding one to this number gives us the next frame. We will interpolate these two frame to find the current frame skeleton, in order to keep a nice smooth animation. When interpolating two things, we have to have an interpolation factor, which we can get by finding the remainder from the current animation time multiplied with the framerate (eg. currentFrameTime = 5.3667, currentFrame = 5, interpolationFactor = 0.3667).


void UpdateMD5Model(Model3D& MD5Model, float deltaTime, int animation)
{
	MD5Model.animations[animation].currAnimTime += deltaTime;			// Update the current animation time

	if(MD5Model.animations[animation].currAnimTime > MD5Model.animations[animation].totalAnimTime)
		MD5Model.animations[animation].currAnimTime = 0.0f;

	// Which frame are we on
	float currentFrame = MD5Model.animations[animation].currAnimTime * MD5Model.animations[animation].frameRate;	
	int frame0 = floorf( currentFrame );
	int frame1 = frame0 + 1;

	// Make sure we don't go over the number of frames	
	if(frame0 == MD5Model.animations[animation].numFrames-1)
		frame1 = 0;

	float interpolation = currentFrame - frame0;	// Get the remainder (in time) between frame0 and frame1 to use as interpolation factor

	std::vector<Joint> interpolatedSkeleton;		// Create a frame skeleton to store the interpolated skeletons in

Computing the Interpolated Skeleton

Now we can create the interpolated skeleton. This is actually pretty easy to do. You can see by the code the equation we use to find the interpolated position of the joints, and then below use a technique called spherical linear interpolation (Slerp) to interpolate the two quaternions representing the two joints' orientation. We can use a function called XMQuaternionSlerp() to interpolate two quaternions based on the interpolation factor.


	// Compute the interpolated skeleton
	for( int i = 0; i < MD5Model.animations[animation].numJoints; i++)
	{
		Joint tempJoint;
		Joint joint0 = MD5Model.animations[animation].frameSkeleton[frame0][i];		// Get the i'th joint of frame0's skeleton
		Joint joint1 = MD5Model.animations[animation].frameSkeleton[frame1][i];		// Get the i'th joint of frame1's skeleton

		tempJoint.parentID = joint0.parentID;											// Set the tempJoints parent id

		// Turn the two quaternions into XMVECTORs for easy computations
		XMVECTOR joint0Orient = XMVectorSet(joint0.orientation.x, joint0.orientation.y, joint0.orientation.z, joint0.orientation.w);
		XMVECTOR joint1Orient = XMVectorSet(joint1.orientation.x, joint1.orientation.y, joint1.orientation.z, joint1.orientation.w);

		// Interpolate positions
		tempJoint.pos.x = joint0.pos.x + (interpolation * (joint1.pos.x - joint0.pos.x));
		tempJoint.pos.y = joint0.pos.y + (interpolation * (joint1.pos.y - joint0.pos.y));
		tempJoint.pos.z = joint0.pos.z + (interpolation * (joint1.pos.z - joint0.pos.z));

		// Interpolate orientations using spherical interpolation (Slerp)
		XMStoreFloat4(&tempJoint.orientation, XMQuaternionSlerp(joint0Orient, joint1Orient, interpolation));

		interpolatedSkeleton.push_back(tempJoint);		// Push the joint back into our interpolated skeleton
	}

Calculate the Vertex Position and Normal

Now we loop through each subset in the model, then another loop for each vertex, and finally another one for each of the vertex's weights. To calculate the vertex position, we do the same thing we did in the last lesson when creating our bind-pose model. After we calculate the vertex's position, we calculate its normal. We can calculate the normal by first finding the weights normal. To find the weights normal, we just rotate the normal based on the joints orientation. After we have the weight normal, we multiply it by the weights bias factor, and finally add it to the vertex normal.


	for ( int k = 0; k < MD5Model.numSubsets; k++)
	{
		for ( int i = 0; i < MD5Model.subsets[k].vertices.size(); ++i )
		{
			Vertex tempVert = MD5Model.subsets[k].vertices[i];
			tempVert.pos = XMFLOAT3(0, 0, 0);	// Make sure the vertex's pos is cleared first
			tempVert.normal = XMFLOAT3(0,0,0);	// Clear vertices normal

			// Sum up the joints and weights information to get vertex's position and normal
			for ( int j = 0; j < tempVert.WeightCount; ++j )
			{
				Weight tempWeight = MD5Model.subsets[k].weights[tempVert.StartWeight + j];
				Joint tempJoint = interpolatedSkeleton[tempWeight.jointID];

				// Convert joint orientation and weight pos to vectors for easier computation
				XMVECTOR tempJointOrientation = XMVectorSet(tempJoint.orientation.x, tempJoint.orientation.y, tempJoint.orientation.z, tempJoint.orientation.w);
				XMVECTOR tempWeightPos = XMVectorSet(tempWeight.pos.x, tempWeight.pos.y, tempWeight.pos.z, 0.0f);

				// We will need to use the conjugate of the joint orientation quaternion
				XMVECTOR tempJointOrientationConjugate = XMQuaternionInverse(tempJointOrientation);

				// Calculate vertex position (in joint space, eg. rotate the point around (0,0,0)) for this weight using the joint orientation quaternion and its conjugate
				// We can rotate a point using a quaternion with the equation "rotatedPoint = quaternion * point * quaternionConjugate"
				XMFLOAT3 rotatedPoint;
				XMStoreFloat3(&rotatedPoint, XMQuaternionMultiply(XMQuaternionMultiply(tempJointOrientation, tempWeightPos), tempJointOrientationConjugate));

				// Now move the verices position from joint space (0,0,0) to the joints position in world space, taking the weights bias into account
				tempVert.pos.x += ( tempJoint.pos.x + rotatedPoint.x ) * tempWeight.bias;
				tempVert.pos.y += ( tempJoint.pos.y + rotatedPoint.y ) * tempWeight.bias;
				tempVert.pos.z += ( tempJoint.pos.z + rotatedPoint.z ) * tempWeight.bias;

				// Compute the normals for this frames skeleton using the weight normals from before
				// We can comput the normals the same way we compute the vertices position, only we don't have to translate them (just rotate)
				XMVECTOR tempWeightNormal = XMVectorSet(tempWeight.normal.x, tempWeight.normal.y, tempWeight.normal.z, 0.0f);

				// Rotate the normal
				XMStoreFloat3(&rotatedPoint, XMQuaternionMultiply(XMQuaternionMultiply(tempJointOrientation, tempWeightNormal), tempJointOrientationConjugate));

				// Add to vertices normal and ake weight bias into account
				tempVert.normal.x -= rotatedPoint.x * tempWeight.bias;
				tempVert.normal.y -= rotatedPoint.y * tempWeight.bias;
				tempVert.normal.z -= rotatedPoint.z * tempWeight.bias;
			}

			MD5Model.subsets[k].positions[i] = tempVert.pos;				// Store the vertices position in the position vector instead of straight into the vertex vector
			MD5Model.subsets[k].vertices[i].normal = tempVert.normal;		// Store the vertices normal
			XMStoreFloat3(&MD5Model.subsets[k].vertices[i].normal, XMVector3Normalize(XMLoadFloat3(&MD5Model.subsets[k].vertices[i].normal)));
		}

Updating the Buffer

The last thing we do in this function is update the vertex buffer. We have created a dynamic vertex buffer if you can remember from the last lesson. To update the dynamic buffers in directx, we need to first lock them, then copy the contents that we want into the buffer. The map function returns a filled out D3D11_MAPPED_SUBRESOURCE object, where the pData member of D3D11_MAPPED_SUBRESOURCE is a pointer to the beginning of the data in the buffer. We can use this pointer to copy our vertex array to the buffer, then finally unmapping the buffer. Notice how when copying a vector to a buffer, you must use its pointer, and it's pointer must be pointing to the first element ([0]) that you want to start copying. This is because a pointer directly to the beginning of a vector will point to a bunch of extra stuff used to describe the vector or something.

I kept this in the code for reference, but if you are using a default buffer, you can update that buffer using the UpdateSubresource function, although you would only want to do this kind of updating not very often since it's much slower than using a dynamic buffer.


		// Put the positions into the vertices for this subset
		for(int i = 0; i < MD5Model.subsets[k].vertices.size(); i++)
		{
			MD5Model.subsets[k].vertices[i].pos = MD5Model.subsets[k].positions[i];
		}

		// Update the subsets vertex buffer
		// First lock the buffer
		D3D11_MAPPED_SUBRESOURCE mappedVertBuff;
		hr = d3d11DevCon->Map(MD5Model.subsets[k].vertBuff, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedVertBuff);

		// Copy the data into the vertex buffer.
		memcpy(mappedVertBuff.pData, &MD5Model.subsets[k].vertices[0], (sizeof(Vertex) * MD5Model.subsets[k].vertices.size()));

		d3d11DevCon->Unmap(MD5Model.subsets[k].vertBuff, 0);

		// The line below is another way to update a buffer. You will use this when you want to update a buffer less
		// than once per frame, since the GPU reads will be faster (the buffer was created as a DEFAULT buffer instead
		// of a DYNAMIC buffer), and the CPU writes will be slower. You can try both methods to find out which one is faster
		// for you. if you want to use the line below, you will have to create the buffer with D3D11_USAGE_DEFAULT instead
		// of D3D11_USAGE_DYNAMIC
		//d3d11DevCon->UpdateSubresource( MD5Model.subsets[k].vertBuff, 0, NULL, &MD5Model.subsets[k].vertices[0], 0, 0 );
	}
}

Call the LoadMD5Model() Function

Now all thats left is to call the function that will load in our models animation!


	if(!LoadMD5Anim(L"boy.md5anim", NewMD5Model))
		return false;

This should give you at least some useful information! hope you enjoyed it!

Exercise:

1. Try to update the structures so that you can use a loaded animation for multiply models (as long as they have the same joint hierarchy).

2. Instead of having the guy run in a single spot, have him run in circles or a pattern of your choosing!

3. Let me know what you think!

4. Have a great day!

>> Download Source Code <<
<<-- Loading in an MD5 Model (.md5mesh)
New Lesson -->>



- Comments will not be seen by public -

- Please be sure to put your email in the message if you'd like a response -

whats 7 - 3:
Name:
Message: