Introduction to Avatars (XNA Game Studio 4.0 Programming)

The avatar APIs in XNA Game Studio 4.0 provide a high-level abstraction that provides the capability to animate and render avatars with a simple API.The process of loading and managing the models and textures used to draw the avatars is hidden from the developer. Figure 10.1 shows what a avatar looks like.

Example of a player's avatar

Figure 10.1 Example of a player’s avatar

The avatar functionality is included in the Microsoft.Xna.Framework.Avatars assembly, which is available to the Xbox 360 and Windows platforms.Although the assembly is available on Windows, it is not possible to draw avatars on Windows. The Windows APIs are provided to minimize the amount of platform-specific defines needed in your code.

Accessing Avatar Information Using AvatarDescription

An avatar has many customizable components from gender, height, size, clothing, and accessories. Each user has his or her own AvatarDescription that stores all of the customizable choices the user has made when building the avatar.The AvatarDescription contains an internal opaque data buffer that stores all of these choices.The AvatarDescription is used to tell the AvatarRender which model assets and textures should be used for a specific avatar.


Accessing a Gamer’s AvatarDescription

The AvatarDescription class provides an asynchronous method BeginGetFromGamer to access the AvatarDescription for any type that inherits from the Gamer base type.The most common scenario in your game is to load the AvatarDescription for one of the SignedInGamer players in your game.

Let’s see how to access an AvatarDescription from a SignedInGamer. First, add a member variable to your games class to store the AvatarDescription.

tmp14-128_thumb

Next, in the games constructor, add the following two lines of code.

tmp14-129_thumb

The first line adds the GamerServiceComponent to the game’s Components list.This ensures that the GamerServicesDispatcher is regularly updated as the game runs.

The second line creates a new event handler that is fired anytime a player signs into the game. Even if a player is signed into Xbox when your game launches, the SignedInGamers collection will not populate for a number of frames.You can poll the collection yourself, but signing up for this event ensures you are notified anytime a player signs into the console.

The next bit of code to add is the new SignedInGamer_SignedIn method that is called when the SignedIn event fires.Add the following method to your game class:

tmp14-130_thumb

For this example, you want to request only the first player’s AvatarDescription, so check the SignedInEventArgs PlayerIndex property to see whether this event was fired for the first player. If you have the correct player, you then kick off the BeginGetFromGamer asynchronous method. BeginGetFromGamer is passed the instance of the Gamer object and a AsyncCallback method that you will implement.

To implement the LoadGamerAvatar AsyncCallback method, add the following method to your game’s class.

tmp14-131_thumb

In the callback method, first call EndGetFromGamer method, which returns AvatarDescription.After the AvatarDescription has been returned, it is possible that the user did not have a valid avatar set for his or her profile. In that case, the IsValid property returns false. On Windows the returned AvatarDescription always returns false for IsValid.

Creating a Random AvatarDescription

Along with the players’ avatars, you might also want to display more avatars to represent other nonpayer characters in your game. In that case, you can create random avatars.

To create a random AvatarDescription, the static CreateRandom method is provided.

tmp14-132_thumb

This creates either a random female or male avatar that your game can then use. If you want to specify a gender for the avatar, you can use the CreateRandom overload, which takes an AvatarBodyType enumeration argument. The AvatarBodyType enumeration has two values of Female and Male.

tmp14-133_thumb

The AvatarDescription.BodyType property can be used to determine the gender of an existing AvatarDescription. It returns the AvatarBodyType for the already created AvatarDescription.

The AvatarDescription.Height property returns a float value representing the avatar’s height in meters.This is the size of the avatar skeleton from the bottom of the feet to the top of the head.This does not take into account any type of hat or other clothing item that might be on the head.

Constructing an AvatarDescription from a Byte Array

The AvatarDescription class provides a third way to create a new instance of the type. It provides a constructor that takes the opaque description as a byte array. This constructor can be useful in a couple of scenarios.The first is to enable the player to select random characters in your game and then save his or her selection so the same avatar can be used across play sessions.

To obtain the byte array from the existing AvatarDescription, use the following Description property:

tmp14-134_thumb

The second scenario where the byte array constructor is useful is for customizing the nonplayer character avatars in your game. For example, you have a shopkeeper in your game that you want to customize to have a beard and top hat. This can be accomplished by first customizing the avatar in the dashboard avatar editor. Then, load the AvatarDescription for that player. Next, use the debugger to print out the Description property to the debugger. Figure 10.2 shows the AvatarDescription in the debug window.

You can then copy, paste, and format the values into a byte array in your source code. This hard-coded array can then be used to create a new instance of the AvatarDescription.

Description property in the debugger

Figure 10.2 Description property in the debugger

Note

Xbox Live Indie Games prohibits utilizing avatar clothing and other assets that have been unlocked or purchased through the avatar marketplace unless they are outfitted on the player’s avatar. So if you are creating a custom avatar for a nonplayer character, you are restricted in using only the built-in avatar assets and can’t use items you purchased from the avatar marketplace.

The Changed Event

AvatarDescription provides an event called Changed.This event can fire while your game is running in the event that the user has updated his or her avatar.

Loading Avatar Animations with AvatarAnimation

There are a number of built-in animations that enable you to quickly animate an avatar in your game. The animations that are provided were created for use in the Xbox dashboard and consist of idle animations along with some expressive animations like celebrate and clap.

To add an animation to your game, the first thing you need is a new member variable in your game to hold the animation. Add the following member variable to your game:

tmp14-136_thumb

Next, in the game’s LoadContent method, you can load the following celebrate animation:

tmp14-137_thumb

The AvatarAnimation constructor takes an AvatarAnimationPreset enumeration to specify which animation to load.Table 10.1 shows all of the built-in animation types that are defined by the AvatarAnimationPreset enumeration.

Table 10.1 AvatarAnimationPreset Enumerations

Celebrate

MaleIdleCheckHand

Clap

MaleIdleLookAround

FemaleAngry

MaleIdleShiftWeight

FemaleConfused

MaleIdleStretch

FemaleCry

MaleLaugh

FemaleldleCheckNails

MaleSurprised

FemaleldleFixShoe

MaleYawn

FemaleIdleLookAround

Stand0

FemaleIdleShiftWeight

Stand1

FemaleLaugh

Stand2

FemaleShocked

Stand3

FemaleShocked

Stand4

FemaleYawn

Stand5

MaleAngry

Stand6

MaleConfused

Stand7

MaleCry

Wave

Updating the Animation

There are two methods that you can use to update the current playback position of the animation.The first and easiest way is to use the Update method.The Update method takes a TimeSpan for the current frame’s elapsed time and a boolean value that indicates whether the animation should be looped when it reaches the end ofthe animation. To update the animation, add the following to your game’s Update method:

tmp14-138_thumb

The gameTime.ElapsedGameTime TimeSpan is used for the current frame’s length. This updates the animation in sync with how fast your game is updating. The value of true is passed for the loop argument so that the animation loops when it reaches the end of the animation.

The second method for updating the avatar’s playback location is to set the value explicitly.The AvatarAnimation CurrentPosition property is a TimeSpan value that represents the amount of time from the start of the animation.This value can be set to any valid range from 0 to the end length of the animation.The length of the animation can be retrieved by using the Length property of the animation.

Transforms and Expression of the Animation

The animation returns two sets of values for the current playback position.The first is the location for each of the bones in the avatar skeleton.The BoneTransforms property returns a ReadOnlyCollection of Matrix values for each of the bone positions and orientations.

The second set of animation values are for the textures to use for the avatar’s face. Although the body uses skeletal animation to transform the vertices of the avatar, the face is made up of textures for the eyes, eyebrows, and mouth.The AvatarAnimation provides the Expression property to return an AvatarAnimation structure.

The AvatarAnimation structure provides properties for the LeftEye, RightEye, LeftEyebrow, RightEyebrow, and Mouth. Each of these represents the texture to use for the corresponding facial feature.

Table 10.2 shows the AvatarEye enumeration values.

Table 10.2 AvatarEye Enumerations

Angry

LookRight

Blink

LookUp

Confused

Neutral

Happy


Sad

Laughing

Shocked

LookDown

Sleeping

LookLeft

Yawning

Table 10.3 shows the AvatarEyebrow enumeration values. Table 10.3 AvatarEyebrow Enumerations

Angry

Raised

Confused

Sad

Neutral

Table 10.4 shows the AvatarMouth enumeration values. Table 10.4 AvatarMouth Enumerations

Angry

PhoneticEe

Confused

PhoneticFv

Happy

PhoneticL

Laughing

PhoneticO

Neutral

PhoneticW

PhoneticAi

Sad

PhoneticDth

Shocked

Avatar Animation Functionality Though an Interface

Although the built-in avatar animations are convenient, you might want to provide your own custom animations or to programmatically generate animations using IK. The IAvatarAnimation interface is provided to enable you to create your own custom avatar playback systems that work with the avatar system.

The IAvatarAnimation interface exposes four properties: BoneTransforms, CurrentPosition, Expression, and Length. It also exposes one method: Update.The built-in AvatarAnimation type implements the IAvatarAnimation interface so you can combine your animation playback system with the built-in animations.

You learn more about implanting a custom animation playback system that uses the IAvatarAnimation interface later in this topic.

Drawing the Avatar Using AvatarRenderer

Now that you have loaded the AvatarDescription and have an AvatarAnimation to play, you just need models and textures for the avatar and draw them to the screen. This is precisely what the AvatarRenderer type does.

To draw the avatar in the game, you need to add a member variable to store the AvatarRenderer.Add the following member variables to your game class:

tmp14-139_thumb

In the game’s LoadContent method, create an instance of the AvatarRenderer from one of the previous AvatarDescription instances you created previously.

tmp14-140_thumb

After creating a new instance of the AvatarRenderer, set default values for the world, view, and projection matrices. By default, the avatar faces in the negative Z direction, so set the world matrix to rotate around the Y axis.

If you are using the asynchronous AvatarDescription.BeginGetFromGamer method, then you can load the AvatarRenderer in the AsyncCallback method that you pass to BeginGetFromGamer.

The last bit of code is to draw the avatar. In your game’s Draw method add the following lines of code:

tmp14-141_thumb

Before you draw, first set the World, View, and Projection matrices on the AvatarRenderer instance.You can simply call the Draw method passing in any AvatarAnimation or other type that implements the IAvatarAnimation interface. Running the sample should look like Figure 10.3.

Avatar rendering animated with the celebrate animation Drawing While Loading an Avatar

Figure 10.3 Avatar rendering animated with the celebrate animation Drawing While Loading an Avatar

Although the AvatarRenderer constructor is not asynchronous and it returns immediately the loading, the geometry and textures that make up the avatar can take a few frames. During that time, if you call the Draw method, notice an animated swirling pattern like that shown in Figure 10.4.

Avatar loading effect

Figure 10.4 Avatar loading effect

If you don’t want to display the loading effect, you can use the overload ofthe AvatarRenderer constructor that takes a boolean value for the useLoadingEffect parameter. Passing in false causes the loading effect to not display while the avatar is loading.

Deterring the Current State of the AvatarRenderer

At times, you might want to query the state of the AvatarRenderer to see whether it has completed loading.The State property can be used to determine the current state of an AvatarRenderer instance.The return value is an AvatarRendererState enumeration that can have three values of Loading, Ready, and Unavailable.The Loading and Ready states are self-explanatory.The Unavailable state is a special case that occurs in a couple of situ-ations.The first is on Windows when any AvatarRenderer instance returns Unavailable because avatars can’t be rendered on Windows.The second situation is when the models and textures that make up the avatar are corrupted on the Xbox and can’t be downloaded.

Note

When avatars were first introduced, their proportions were not close to those of a real person. For example, their arms were too short. To help support player mapping between their avatar and their body using Kinect, the proportions of the avatars were updated to better match those of a human. The new avatars are referred to as V2 avatars. XNA Game Studio 4.0 utilizes V2 avatars.

Next post:

Previous post: