# DirectX/10.0/Direct3D/Initializing DirectX

This tutorial will be the first introduction to working with DirectX 11. We will address how to initialize and shut down Direct3D as well as how to render to a window.

## Updated Framework

We are going to add another class to the framework which will handle all the Direct3D system functions. We will call the class D3DClass. I have updated the framework diagram below:
As you can see the D3DClass will be located inside the GraphicsClass. The previous tutorial mentioned that all new graphics related classes will be encapsulated in the GraphicsClass and that is why it is the best location for the new D3DClass. Now lets take a look at the changes made to the GraphicsClass:

## Graphicsclass.h

Here is the first change. We have taken out the include for windows.h and instead included the new d3dclass.h.
And the second change is the new private pointer to the D3DClass which we have called m_D3D.
In case you were wondering I use the prefix m_ on all class variables.
That way when I'm coding I can remember quickly what variables are members of the class and which are not.

## Graphicsclass.cpp

If you'll remember from the previous tutorial this class was entirely empty with no code in it at all. Now that we have a D3DClass member we will start to fill out some code inside the GraphicsClass to initialize and shutdown the D3DClass object. We will also add calls to BeginScene and EndScene in the Render function so that we are now drawing to the window using Direct3D.
So the very first change is in the class constructor. Here we initialize the pointer to null for safety reasons as we do with all class pointers.
The second change is in the Initialize function inside the GraphicsClass. Here we create the D3DClass object and then call the D3DClass Initialize function. We send this function the screen width, screen height, handle to the window, and the four global variables from the Graphicsclass.h file. The D3DClass will use all these variables to setup the Direct3D system. We'll go into more detail about that once we look at the d3dclass.cpp file.
The next change is in the Shutdown function in the GraphicsClass.
Shut down of all graphics objects occur here so we have placed the D3DClass shutdown in this function. Note that I check to see if the pointer was initialized or not. If it wasn't we can assume it was never set up and not try to shut it down. That is why it is important to set all the pointers to null in the class constructor. If it does find the pointer has been initialized then it will attempt to shut down the D3DClass and then clean up the pointer afterwards.
The Frame function has been updated so that it now calls the Render function each frame.
The final change to this class is in the Render function. We call the D3D object to clear the screen to a grey color. After that we call EndScene so that the grey color is presented to the window.
Now lets take a look at the new D3DClass header file:

## D3dclass.h

First thing in the header is to specify the libraries to link when using this object module. These libraries contain all the Direct3D functionality for setting up and drawing 3D graphics in DirectX as well as tools to interface with the hardware on the computer to obtain information about the refresh rate of the monitor, the video card being used, and so forth. You will notice that some DirectX 10 libraries are still used, this is because those libraries were never upgraded for DirectX 11 as their functionality did not need to change.
The next thing we do is include the headers for those libraries that we are linking to this object module as well as headers for DirectX type definitions and such.
The class definition for the D3DClass is kept as simple as possible here. It has the regular constructor, copy constructor, and destructor. Then more importantly it has the Initialize and Shutdown function. This will be what we are mainly focused on in this tutorial. Other than that I have a couple helper functions which aren't important to this tutorial and a number of private member variables that will be looked at when we examine the d3dclass.cpp file. For now just realize the Initialize and Shutdown functions are what concerns us.
For those familiar with Direct3D already you may notice I don't have a view matrix variable in this class. The reason being is that I will be putting it in a camera class that we will be looking at in future tutorials.

## D3dclass.cpp

So like most classes we begin with initializing all the member pointers to null in the class constructor. All pointers from the header file have all been accounted for here.
The Initialize function is what does the entire setup of Direct3D for DirectX 11.
I have placed all the code necessary in here as well as some extra stuff that will facilitate future tutorials. I could have simplified it and taken out some items but it is probably better to get all of this covered in a single tutorial dedicated to it.
The screenWidth and screenHeight variables that are given to this function are the width and height of the window we created in the SystemClass. Direct3D will use these to initialize and use the same window dimensions. The hwnd variable is a handle to the window. Direct3D will need this handle to access the window previously created. The fullscreen variable is whether we are running in windowed mode or fullscreen. Direct3D needs this as well for creating the window with the correct settings. The screenDepth and screenNear variables are the depth settings for our 3D environment that will be rendered in the window.
The vsync variable indicates if we want Direct3D to render according to the users monitor refresh rate or to just go as fast as possible.
Before we can initialize Direct3D we have to get the refresh rate from the video card/monitor. Each computer may be slightly different so we will need to query for that information. We query for the numerator and denominator values and then pass them to DirectX during the setup and it will calculate the proper refresh rate. If we don't do this and just set the refresh rate to a default value which may not exist on all computers then DirectX will respond by performing a blit instead of a buffer flip which will degrade performance and give us annoying errors in the debug output.
We now have the numerator and denominator for the refresh rate. The last thing we will retrieve using the adapter is the name of the video card and the amount of memory on the video card.
Now that we have stored the numerator and denominator for the refresh rate and the video card information we can release the structures and interfaces used to get that information.
Now that we have the refresh rate from the system we can start the DirectX initialization. The first thing we'll do is fill out the description of the swap chain. The swap chain is the front and back buffer to which the graphics will be drawn. Generally you use a single back buffer, do all your drawing to it, and then swap it to the front buffer which then displays on the user's screen. That is why it is called a swap chain.
The next part of the description of the swap chain is the refresh rate. The refresh rate is how many times a second it draws the back buffer to the front buffer. If vsync is set to true in our graphicsclass.h header then this will lock the refresh rate to the system settings (for example 60hz).
That means it will only draw the screen 60 times a second (or higher if the system refresh rate is more than 60). However if we set vsync to false then it will draw the screen as many times a second as it can, however this can cause some visual artifacts.
After setting up the swap chain description we also need to setup one more variable called the feature level. This variable tells DirectX what version we plan to use. Here we set the feature level to 11.0 which is DirectX 11. You can set this to 10 or 9 to use a lower level version of DirectX if you plan on supporting multiple versions or running on lower end hardware.
Now that the swap chain description and feature level have been filled out we can create the swap chain, the Direct3D device, and the Direct3D device context. The Direct3D device and Direct3D device context are very important, they are the interface to all of the Direct3D functions.
We will use the device and device context for almost everything from this point forward.
Those of you reading this who are familiar with the previous versions of DirectX will recognize the Direct3D device but will be unfamiliar with the new Direct3D device context. Basically they took the functionality of the Direct3D device and split it up into two different devices so you need to use both now.
Note that if the user does not have a DirectX 11 video card this function call will fail to create the device and device context. Also if you are testing DirectX 11 functionality yourself and don't have a DirectX 11 video card then you can replace D3D_DRIVER_TYPE_HARDWARE with D3D_DRIVER_TYPE_REFERENCE and DirectX will use your CPU to draw instead of the video card hardware. Note that this runs 1/1000 the speed but it is good for people who don't have DirectX 11 video cards yet on all their machines.
Sometimes this call to create the device will fail if the primary video card is not compatible with DirectX 11. Some machines may have the primary card as a DirectX 10 video card and the secondary card as a DirectX 11 video card. Also some hybrid graphics cards work that way with the primary being the low power Intel card and the secondary being the high power Nvidia card. To get around this you will need to not use the default device and instead enumerate all the video cards in the machine and have the user choose which one to use and then specify that card when creating the device.
Now that we have a swap chain we need to get a pointer to the back buffer and then attach it to the swap chain. We'll use the CreateRenderTargetView function to attach the back buffer to our swap chain.
We will also need to set up a depth buffer description.
We'll use this to create a depth buffer so that our polygons can be rendered properly in 3D space. At the same time we will attach a stencil buffer to our depth buffer. The stencil buffer can be used to achieve effects such as motion blur, volumetric shadows, and other things.
Now we create the depth/stencil buffer using that description. You will notice we use the CreateTexture2D function to make the buffers, hence the buffer is just a 2D texture. The reason for this is that once your polygons are sorted and then rasterized they just end up being colored pixels in this 2D buffer. Then this 2D buffer is drawn to the screen.
Now we need to setup the depth stencil description. This allows us to control what type of depth test Direct3D will do for each pixel.
With the description filled out we can now create a depth stencil state.
With the created depth stencil state we can now set it so that it takes effect. Notice we use the device context to set it.
The next thing we need to create is the description of the view of the depth stencil buffer.
We do this so that Direct3D knows to use the depth buffer as a depth stencil texture. After filling out the description we then call the function CreateDepthStencilView to create it.
With that created we can now call OMSetRenderTargets. This will bind the render target view and the depth stencil buffer to the output render pipeline. This way the graphics that the pipeline renders will get drawn to our back buffer that we previously created. With the graphics written to the back buffer we can then swap it to the front and display our graphics on the user's screen.
Now that the render targets are setup we can continue on to some extra functions that will give us more control over our scenes for future tutorials. First thing is we'll create is a rasterizer state. This will give us control over how polygons are rendered.
We can do things like make our scenes render in wireframe mode or have DirectX draw both the front and back faces of polygons. By default DirectX already has a rasterizer state set up and working the exact same as the one below but you have no control to change it unless you set up one yourself.
The viewport also needs to be setup so that Direct3D can map clip space coordinates to the render target space.
Set this to be the entire size of the window.
Now we will create the projection matrix.
The projection matrix is used to translate the 3D scene into the 2D viewport space that we previously created. We will need to keep a copy of this matrix so that we can pass it to our shaders that will be used to render our scenes.
We will also create another matrix called the world matrix. This matrix is used to convert the vertices of our objects into vertices in the 3D scene. This matrix will also be used to rotate, translate, and scale our objects in 3D space. From the start we will just initialize the matrix to the identity matrix and keep a copy of it in this object. The copy will be needed to be passed to the shaders for rendering also.
This is where you would generally create a view matrix. The view matrix is used to calculate the position of where we are looking at the scene from. You can think of it as a camera and you only view the scene through this camera. Because of its purpose I am going to create it in a camera class in later tutorials since logically it fits better there and just skip it for now.
And the final thing we will setup in the Initialize function is an orthographic projection matrix. This matrix is used for rendering 2D elements like user interfaces on the screen allowing us to skip the 3D rendering. You will see this used in later tutorials when we look at rendering 2D graphics and fonts to the screen.
The Shutdown function will release and clean up all the pointers used in the Initialize function, its pretty straight forward. However before doing that I put in a call to force the swap chain to go into windowed mode first before releasing any pointers. If this is not done and you try to release the swap chain in full screen mode it will throw some exceptions. So to avoid that happening we just always force windowed mode before shutting down Direct3D.
In the D3DClass I have a couple helper functions. The first two are BeginScene and EndScene. BeginScene will be called whenever we are going to draw a new 3D scene at the beginning of each frame. All it does is initializes the buffers so they are blank and ready to be drawn to.
The other function is Endscene, it tells the swap chain to display our 3D scene once all the drawing has completed at the end of each frame.
These next functions simply get pointers to the Direct3D device and the Direct3D device context.
These helper functions will be called by the framework often.
The next three helper functions give copies of the projection, world, and orthographic matrices to calling functions. Most shaders will need these matrices for rendering so there needed to be an easy way for outside objects to get a copy of them. We won't call these functions in this tutorial but I'm just explaining why they are in the code.
The last helper function returns by reference the name of the video card and the amount of dedicated memory on the video card. Knowing the video card name and amount of video memory can help in debugging on different configurations.

## Summary

So now we are finally able to initialize and shut down Direct3D as well as render a color to the window. Compiling and running the code will produce the same window as the last tutorial but Direct3D is initialized now and the window is cleared to grey. Compiling and running the code will also show if your compiler is set up properly and if it can see the headers and libraries files from the DirectX SDK.

## To Do Exercises

1. Re-compile the code and run the program to ensure DirectX works, if not look at the steps from the first tutorial.
Press the escape key to quit after the window displays.
2. Change the global in graphicsclass.h to full screen and re-compile/run.
3. Change the clear color in GraphicsClass::Render to yellow.
4. Write the video card name and memory out to a text file.