This project has moved and is read-only. For the latest updates, please go here.
NEWS: This project is now hosted on GitHub https://github.com/Microsoft/DirectXTK. This site is being maintained for now, but please move to using GitHub https://github.com/Microsoft/DirectXTK/wiki/Rendering-a-model particularly as the CodePlex copy of the tutorials are a little dated.

This lesson loads and draws models in 3D.

Setup

First create a new project using the instructions from the first two lessons: The basic game loop and
Adding the DirectX Tool Kit which we will use for this lesson.

Creating a model

Source assets for models are often stored in Autodesk FBX, Wavefront OBJ, or similar formats. A build process is used to convert them to a more run-time friendly format that is easier to load and render.

Visual Studio has a built-in system for converting a Wavefront OBJ or Autodesk FBX as part of the build process to a CMO, which you can read about here - http://msdn.microsoft.com/en-us/library/hh972446.aspx.

For this tutorial, we will instead make of use of the DirectXMesh (http://go.microsoft.com/fwlink/?LinkID=324981) meshconvert command-line tool. Start by saving cup._obj, cup.mtl, and cup.jpg into your new project's directory, and then from the top menu select Project / Add Existing Item.... Select "cup.jpg" and click "OK".
  1. Download the "Meshconvert.zip" from the DirectXMesh CodePlex site and extract the EXE into your project's folder.
  2. Open a command-prompt and then change to your project's folder. http://windows.microsoft.com/en-us/windows/command-prompt-faq
  3. Run the following command-line
meshconvert cup._obj -cmo -nodds -fliptc -y

Then from the top menu in Visual Studio select Project / Add Existing Item.... Select cup.cmo and click "OK".

Technical notes

  • The switch "-cmo" selects the Visual Studio Compiled Mesh Object runtime format as the output. The meshconver command-line tool also supports "-sdkmesh" and "-vbo". https://directxmesh.codeplex.com/wikipage?title=Geometry%20formats
  • The switch "-nodds" causes any texture file name references in the material information of the source file to stay in their original file format (such as .png or .jpg). Otherwise, it assumes you will be converting all the needed texture files to a .dds instead.
  • The switch "-fliptc" flips the direction of the texture coordinates. Since SimpleMath and these tutorials assume we are using right-handed viewing coordinates and the model was created using left-handed viewing coordinates we have to flip them to get the text in the texture to appear correctly.
  • The switch "-y" indicates that it is ok to overwrite the output file in case you run it multiple times.

Drawing a model

In the Game.h file, add the following variables to the bottom of the Game class's private declarations:

DirectX::SimpleMath::Matrix m_world;
DirectX::SimpleMath::Matrix m_view;
DirectX::SimpleMath::Matrix m_proj;

std::unique_ptr<DirectX::CommonStates> m_states;
std::unique_ptr<DirectX::IEffectFactory> m_fxFactory;
std::unique_ptr<DirectX::Model> m_model;

In Game.cpp, add to the TODO of CreateDevice:

m_states.reset(new CommonStates(m_d3dDevice.Get()));

m_fxFactory.reset(new EffectFactory(m_d3dDevice.Get()));

m_model = Model::CreateFromCMO(m_d3dDevice.Get(), L"cup.cmo", *m_fxFactory);

m_world = Matrix::Identity;

In Game.cpp, add to the TODO of CreateResources:

m_view = Matrix::CreateLookAt(Vector3(2.f, 2.f, 2.f), Vector3::Zero, Vector3::UnitY);
m_proj = Matrix::CreatePerspectiveFieldOfView(XM_PI / 4.f,
    float(backBufferWidth) / float(backBufferHeight), 0.1f, 10.f);

In Game.cpp, add to the TODO of OnDeviceLost:

m_states.reset();
m_fxFactory.reset();
m_model.reset();

In Game.cpp, add to the TODO of Render:

m_model->Draw(m_d3dContext.Get(), *m_states, m_world, m_view, m_proj);

In Game.cpp, add to the TODO of Update:

float time = float(timer.GetTotalSeconds());

m_world = Matrix::CreateRotationZ(cosf(time) * 2.f);

Build and run and you will see our cup model rendered with default lighting:

screenshotCup.png

Troubleshooting: If you get a runtime exception, then you may have the "cup.jpg" or "cup.cmo" in the wrong folder, have modified the "Working Directory" in the "Debugging" configuration settings, or otherwise changed the expected paths at runtime of the application. You should set a break-point on Model::CreateFromCMO and step into the code to find the exact problem.

Updating effects settings in a model

The Model class creates effects automatically for the loaded materials which are set to default lighting parameters. To update them, you use the Model::UpdateEffects method. Because the effects system is flexible, we must first enable C++ Run-Time Type Information (RTTI) in order to safely discover the various interfaces supported at runtime. From the drop-down menu, select Project / Properties. Set to "All Configurations" / "All Platforms". On the left-hand tree view select C/C++ / Language. Then set "Enable Run-Time Type Information" to "Yes". Click "OK".

settingsRTTI.png

In Game.cpp, add to the TODO of CreateDevice:

m_model->UpdateEffects([](IEffect* effect)
{
    auto lights = dynamic_cast<IEffectLights*>(effect);
    if (lights)
    {
        lights->SetLightingEnabled(true);
        lights->SetPerPixelLighting(true);
        lights->SetLightEnabled(0, true);
        lights->SetLightDiffuseColor(0, Colors::Gold);
        lights->SetLightEnabled(1, false);
        lights->SetLightEnabled(2, false);
    }

    auto fog = dynamic_cast<IEffectFog*>(effect);
    if (fog)
    {
        fog->SetFogEnabled(true);
        fog->SetFogColor(Colors::CornflowerBlue);
        fog->SetFogStart(3.f);
        fog->SetFogEnd(4.f);
    }
});

Build and run to get our cup with a colored light and fogging enabled.

screenshotCupFog.png

Technical notes

Here we've made use to two C++ concepts:
  1. The dynamic_cast operator allows us to safely determine if an effect in the model supports lighting and/or fog using the C++ run-time type checking. If the IEffect instance does not support the desired interface, the cast returns a nullptr and our code will skip those settings.
  2. This also used a lambda function (aka anonymous function) of the form [](IEffect* effect){ ... } which is a new C++11 syntax. We could have used a C-style call-back function, but this syntax is more direct.

Using DGSL shaders for the model

For this lesson, we made use of EffectFactory which will create BasicEffect, DualTextureEffect, or SkinnedEffect instances depending on the content of the loaded model file. With CMOs and the built-in Visual Studio 3D pipeline, you can instead make use of DGSLEffect by changing EffectFactory to DGSLEffectFactory.

In Game.cpp in the TODO section of CreateDevice, change

m_fxFactory.reset(new EffectFactory(m_d3dDevice.Get()));

to

m_fxFactory.reset(new DGSLEffectFactory(m_d3dDevice.Get()));

Note: This is why we used the abstract interface IEffectFactory rather than using std::unique_ptr<EffectFactory> in Game.h so that the variable could refer to either type of factory.

Build and run. If you still have the UpdateEffects code in place, you'll see the fog no longer appears although the light is colored since DGSLEffect does not support the fog interface.

screenShotCupNoFog.png

The lack of fog is because our "cup.cmo" makes use of the default built-in DGSL shaders lambert and phong which do not implement fog. The DGSLEffectFactory allows you to use Model and the Effect interface with the more complex custom DGSL shaders supported by the Visual Studio CMO pipeline where you use a visual editor to build pixel shaders.

http://msdn.microsoft.com/en-us/library/hh873117.aspx

Next lesson: Using skinned models

Further reading

DirectX Tool Kit docs EffectFactory, Effects, Model

Last edited Jul 28, 2015 at 7:53 PM by walbourn, version 29