Getting started with XNA – Drawing a 3D Model

In the previous tutorials, we’ve learned how to draw primitives and 2D textures. It’s time we step up to drawing a 3D model. To start with this tutorial you’ll need the following source code. It’s just an empty project containing our heads up display. Our 3D model is also located in the content folder. When you click on the forklift.fbx file, notice that it uses the Autodesk FBX – XNA Framework importer and Model – XNA Framework processor.
Forklift.fbx is a 3d model which has been exported from 3D Studio Max. You can find screenshots of the model and the export below.

ForkliftForklift WireframeForkliftForklift WireframeForklift Export

So let’s get started! Add a class to your project and call it Forklift.cs. Then adjust the class so it inherits from DrawableGameComponent. This makes sure that our LoadGraphicsContent, Update and Draw method will be called automatically. When you’re writing a full game, you’ll probably write your own component based system, but for this tutorial, DrawableGameComponent will do just fine.
public class Forklift : DrawableGameComponent

Then we’ll add 3 variables to our class. The first containing the content manager, which will load our content. The second a variable which will contain our model, and last but not least, a variable which will contain the bone transforms of our model (the transform of each bone relative to the parent bone).
// A variable containing our content manager
private ContentManager _content;
// Our model
private Model _model;
// Array holding all the bone transform matrices for the entire model.
// We could just allocate this locally inside the Draw method, but it
// is more efficient to reuse a single array, as this avoids creating
// unnecessary garbage.
Matrix[] _boneTransforms;

Then add the following constructor, where we’ll pass the Game class to the base class and save a reference to our content manager:
public Forklift(Game game, ContentManager content)
: base(game)
{
_content = content;
}

Now there are 2 things we have to do left: load the model and draw it. We’ll load the model in the LoadGraphicsContent method.
protected override void LoadGraphicsContent(bool loadAllContent)
{
_model = _content.Load("Content/forklift");
// Allocate the transform matrix array.
_boneTransforms = new Matrix[_model.Bones.Count];

//rotate the model 90 degrees
_model.Root.Transform *= Matrix.CreateRotationY(MathHelper.ToRadians(90));

base.LoadGraphicsContent(loadAllContent);
}

In the first line, we load our model using the content manager and store it in de _model variable. In the second line we make an instance of our _boneTransforms matrix, and give it the number of bones in the model as size. In the third line, I’m just rotating the model 90 degrees, so we’ll see it from the side instead of from the front. The last line is just there so we’d see the model better ;-) .

That’s it! Our model is loaded, now let’s draw it.
Drawing the model will of course be done in the Draw method. First we’ll copy our absolute bone transforms to our _boneTransforms matrix. Then we’ll loop over all the model’s meshes, and draw them using their effects. An effect is a shader, which tells your graphics card how to draw stuff. Everything in XNA has to be drawn using shaders. We’ll pass the world, view and projection to this shader, and enable default lighting, so our model is lit properly. More on world, view and projection in our camera tutorial.
public override void Draw(GameTime gameTime)
{
_model.CopyAbsoluteBoneTransformsTo(_boneTransforms);
// Draw the model.
foreach (ModelMesh mesh in _model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = _boneTransforms[mesh.ParentBone.Index];
effect.View = Matrix.CreateLookAt(new Vector3(1000, 500, 0),
new Vector3(0, 150, 0),
Vector3.Up);

effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
GraphicsDevice.Viewport.Width / GraphicsDevice.Viewport.Height,
10,
10000);

effect.EnableDefaultLighting();
}

mesh.Draw();
}

base.Draw(gameTime);
}

If you want to know why exactly you have to draw a model like this, check out this post on Shawn Hargreaves Blog.
That’s it! When you run the project, you should see the image shown below.
Drawing a 3D Model

As usual, you can download the complete source code.

In the next tutorials, we’ll animate the model and put in a camera.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

82 thoughts on “Getting started with XNA – Drawing a 3D Model

  1. You really make it appear really easy together with your presentation but I to find this matter to be really
    one thing that I think I might never understand.

    It sort of feels too complicated and very extensive for me.
    I am taking a look ahead on your subsequent submit, I will attempt
    to get the cling of it!

  2. The initial step is sifting over the many agencies selling Facebook likes and pinpointing one which suits your desires and one that is definitely credible.
    Beejive – IM is great because all of your social
    networking apps are integrated so you can chat with all of
    your friends, regardless of what application they are using.

    Passwords which are unmanageable to hack writer are made of letters (majuscule
    + lowercase), numbers pool and particular characters.
    There’s numerous disjoined tragedies that can blaze
    the trail to a custody inside the Stearns county jail in
    Minnesota. That should certainly aid to obtain Google’s +1 button broadly adopted.

  3. Hello There. I found your blog using msn. This is a very well written article.

    I will make sure to bookmark it and come back to read more of your useful info.
    Thanks for the post. I will definitely return.

  4. Each tag has its own webpage, known in Word – Press as a tag archive.
    Google loves to see natural content, and natural content usually links to other
    content. Lastly, it is possible to use visitor blogging
    like a way to have large amounts of hyperlinks for the web sites.

  5. Individual with known hypersensitivity to any of you that are suffering from acne and clogged pores.
    As acne treatment for men we get older. It is mainly
    because of the hormones in dairy acne treatment for men products.
    The pictures above haven’t been touched up or edited however I did put a cheeky flash on so you can always add the other acne treatment for men techniques to.
    The first night after being on holiday is what I would recommend this moisturiser for those with oily complexions.

  6. Thanks a lot for sharing this with all folks you actually understand what you are speaking approximately!
    Bookmarked. Please also seek advice from my web site =).

    We may have a hyperlink trade arrangement between
    us

  7. You are so interesting! I do not suppose I’ve read something like that before.
    So good to discover another person with a few unique thoughts on this
    topic. Seriously.. many thanks for starting this up.
    This site is one thing that is needed on the web, someone with a little originality!

  8. ERROR #2: Not Giving Your Chickens Proper Ventilation.
    He’d anticipated chicken” coop” plans, and he was obtaining actual chicken” coupe” ideas.
    Many coops are built with windows- keeping those cracked can help.

  9. battle camp cheats has a huge function inside U .
    s . Traditions. A lot of people is often observed getting involved
    in activities regarding battle camp hack tool. That is to some extent
    due to the fact folks of most age range might be included and also families are usually added
    together by simply this particular. Generally an individual exactly who shows their
    hate with regard to battle camp hack tool could be
    regarded a great outcast.

  10. Set up a calendar next to your computer screen, if
    possible, so you can keep track of dates and deadlines.
    I make money at home through affiliate marketing and
    you will too. Make sure that the period you’ll be working
    on the project is indicated as well.

  11. But when Grendel is first introduced, there is a specific affliction and reasoning that’s reminiscent of “The Fall of the House of Usher”.
    Were the sons of God really fallen angels or just disobedient descendants of Seth, and did Jesus prophesy
    their return in the Olivet Discourse. There are better Hebrew words that
    the Holy Spirit could have used to describe “fallen princes, aristocrats or great men”.

  12. It is also search engine optimized and can be easily integrated with Buddy –
    Press. To get noticed, your posts also need interesting and
    engaging titles that will hook your readers
    into reading the rest of the article. You can change your website design,
    theme, template and layout, which makes your website user-friendly and more attractive.

  13. I have been surfing online more than 2 hours today,
    yet I never found any interesting article like yours. It is pretty worth enough for me.

    Personally, if all website owners and bloggers made good content as you did, the internet will be much more useful
    than ever before.

  14. Hi there! This is my first comment here so I just wanted to give
    a quick shout out and tell you I truly enjoy reading through your blog posts.
    Can you suggest any other blogs/websites/forums that cover the same topics?
    Thanks a ton!

  15. After looking at a few of the articles on your site,
    I honestly appreciate your way of writing a blog. I book-marked it to my
    bookmark site list and will be checking back soon. Please visit my
    website as well and let me know what you think.

  16. Does your site have a contact page? I’m having trouble locating it but,
    I’d like to send you an email. I’ve got some recommendations for your blog you might be
    interested in hearing. Either way, great website and I look forward to seeing it grow over time.

  17. Howdy! I know this is somewhat off topic but I was wondering which blog platform are you using
    for this site? I’m getting fed up of WordPress because
    I’ve had problems with hackers and I’m looking at options for another
    platform. I would be fantastic if you could point me in the direction of a good platform.

  18. You are so interesting! I do not suppose I have read
    through anything like this before. So nice to discover somebody with a few genuine
    thoughts on this subject. Really.. many thanks for starting this
    up. This site is one thing that is required on the web, someone with some originality!

  19. I was wondering if you ever considered changing the page layout of your website?
    Its very well written; I love what youve got to say. But maybe
    you could a little more in the way of content
    so people could connect with it better. Youve
    got an awful lot of text for only having 1 or two images.
    Maybe you could space it out better?

  20. Hurrah, that’s what I was looking for, what a stuff!

    present here at this web site, thanks admin of this web site.

  21. Hi, i think that i noticed you visited my weblog thus i
    got here to go back the want?.I’m attempting to to find things to improve
    my website!I suppose its adequate to use some of your ideas!!

  22. Hi! I just wanted to ask if you ever have any problems with hackers?

    My last blog (wordpress) was hacked and
    I ended up losing months of hard work due to no data backup.
    Do you have any solutions to stop hackers?

  23. Hi, i think that i noticed you visited my blog so i came
    to go back the desire?.I’m attempting to in finding things
    to impfove my web site!I guess its ok to make use of a ffew of your ideas!!

  24. I do not even know how I ended up here, but I thought this
    post was great. I do not know who you are
    but certainly you are going to a famous blogger if you aren’t already ;) Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>