DirectX/9.0/Direct3D/Initialization

One of the most important and complex parts of Direct3D is initialization. There are two ways to go about it, the correct (read: tedious, hard, annoying, but worth learning) way which the majority of this chapter is on, and the easy way, which will be used as an introduction, as some portions are required no matter how you do it. At the end of this section, we will apply this to our benchmarking application.

The Easy Way
The first thing you must do to begin initializing Direct3D is to create a Direct3D object. This object will be essential throughout the rest of the book. Luckily, that does not mean that it is hard. In fact, the only thing you have to do is call a function

This function returns the address of the IDirect3D9 interface it created, or our Direct3D object. You need to tell it what version of DirectX the SDK is with the parameter. Generally you just pass D3D_SDK_VERSION, unless you want an older interface for some reason.

And that's that. Unfortunately, the rest of the process isn't so easy. The next thing you need is a set of presentation parameters, which are stored in a D3DPRESENT_PARAMETERS structure. If you look inside, you'll notice there are a lot of variables. You don't need to fill them all, not even most of them. Just make sure that they're all zeroed. The only two you're worried about are Windowed, and SwapEffect. For Windowed, you can just set it to true. SwapEffect depends on what you want. For this tutorial, the fastest, D3DSWAPEFFECT_DISCARD, will work fine. As of now, your code should look something like this:

Now we can actually create the device. This can be accomplished with a call to a function referenced by d3dobject:

This returns either 0 (success), or an error. There are many parameters, but most have values which always work. The first is the adapter number. Right now, we can just use D3DADAPTER_DEFAULT, which always works. DeviceType also has a value that always works: D3DDEVTYPE_REF. This is very slow, and should not be used unless absolutely necessary; but for right now, it will suffice (It also does not work without SDK libraries installed, so don't try it on other computers). Our next parameter is our window's handle, which is not covered in this book (See Windows Programming). BehaviorFlags will work with D3DCREATE_SOFTWARE_VERTEXPROCESSING, another slow choice. pPresentationParameters (why does Microsoft use such long names?) gets the address of our present parameters structure, and ppReturnedDeviceInterface gets a pointer to the pointer we want filled. So our call looks like this:

And that's how you initialize a device! Of course, you almost certainly want a faster device with more capabilities, and you really should check for errors so your user doesn't lose memory if your program crashes, but that's covered next.

The Adapter
All (good) commercial games that use DirectX initialize the device the right way. Nearly all (if not all) allow you to choose which graphics card, or adapter, their engine is running on. So that is where we will start. Determining the graphics cards available is very useful. First, it gives a degree of freedom to the user, which is always important. For commercial games, it also allows them to create a list which has settings which work the best with that card, thereby making it easier for the user. We will certainly implement this feature into our benchmark application, albeit only for the first reason. The first thing that you must do (after initializing the IDirect3D9 interface, of course) is determine the number of adapters available. This is a simple function:

It returns the number of adapters available. The next thing we need to do is get an array of the D3DADAPTER_IDENTIFIER9 structures. After creating the array, we can fill it with a loop and a call to:

This returns D3D_OK if the parameters were valid, or D3DERR_INVALIDCALL if something was wrong. The value passed to adapter is can be anything inside [0,GetAdapterCount). Flags should be 0 (unless we want Windows to download new driver certificates, which we don't), and pIdentifier should be the address of the current index. And now here's our code:

We can then choose the adapter our application will use based on which video card the user chooses (using the message handler), or whichever the program thinks is best based on the details in the D3DADAPTER_IDENTIFIER9 structure.

Device Capabilities and Buffer Formats
After we have chosen the adapter, we can find out what it can do with a D3DCAPS9 structure. Unfortunately, this is a somewhat drawn out process. You need to call:

The parameters are a bit tricky. Adapter and pCaps are simple, they're just the adapter number we chose and a pointer to the D3DCAPS structure we need filled. DeviceType is the problem. It must be determined with another function. We can check for a hardware device with:

After calling this, we can check if the device type worked based on whether it returned D3D_OK. The parameters, however, require another piece of information. For Adapter, we give the adapter number. DeviceType is the type we want to check for, and should be D3DDEVTYPE_HAL. Since we are windowed, that should be TRUE. DisplayFormat and BackBufferFormat are what we need to determine, and they should generally (for fullscreen, they must be) should be the same thing. They can be resolved through trial and error in a nested if statement, starting with the format we'd prefer, and going through most of them. Here is a list of valid Display and Back Buffer formats: http://msdn.microsoft.com/en-us/library/bb172558(VS.85).aspx If it never returns D3D_OK, you're stuck with D3DDEVTYPE_REF or D3DDEVTYPE_SW. We'll skip the formats with alpha fields, because they aren't supported by fullscreen, and we'll find the best format for either HAL or REF, because we'll need it later. Here's what our code will look like:

Some people who know how to do this may point out that you could just use IDirect3D9*->GetAdapterDisplayMode to determine a valid format for windowed applications. I did not do this here because it does not work when you're working in fullscreen, and the code above always works. In any case, you now have the device caps for the adapter. What do we do with it? The first thing we can do is find out if the hardware supports transformations or lighting. We can do that with the DevCaps variable in caps. You just need to use some bitwise operations to see if it has D3DDEVCAPS_HWTRANSFORMANDLIGHT. If it does, we will be able to use D3DCREATE_HARDWARE_VERTEXPROCESSING instead of D3DCREATE_SOFTWARE_VERTEXPROCESSING in CreateDevice. We are also able to extract other information about what we can pass through with it, such as D3DCREATE_PUREDEVICE (bad for debugging, very good for speed), which requires hardware.

We can also determine the present intervals we can use. It stores the valid intervals as a bit mask in its PresentationIntervals field. Any of the values on this page can be used: http://msdn.microsoft.com/en-us/library/bb172585(VS.85).aspx. If we want to see if the device supports a certain form, we just do this:

There is more information about the device in the CAPS structure, but it is of little use currently (read: I don't know what to do with it).

Depth Stencils
Obtaining valid a depth stencil is very similar to getting a valid format. It requires a call to

and returns D3D_OK if it was successful. The non-obvious parameters are Usage, RType, and CheckFormat. Usage tells what type of format we are checking; Depth stencils; and should be D3DUSAGE_DEPTHSTENCIL. RType tells what form of resource we are using, and should be D3DRTYPE_SURFACE. CheckFormat is the depth stencil format we want to check. Determining this requires another trial and error approach; and uses the formats with a "D" in the name at the format list: http://msdn.microsoft.com/en-us/library/bb172558(VS.85).aspx. Here's an example:

Multisampling
Multisampling is yet another trial and error procedure, and luckily the last one. We'll be determining two values to use: the multisampling level and the maximum quality of multisampling. These are both determined with this function:

CheckDeviceMultiSampleType returns D3D_OK if the multisampling typw is valid. It also gives us the maximum quality level in pQualityLevels. Our D3DFORMAT parameter should be our back buffer format, and pQualityLevels should be the address of a DWORD. D3DMULTISAMPLE_TYPE can be any of the values listed here: http://msdn.microsoft.com/en-us/library/bb172574(VS.85).aspx As always, here's our example usage:

Display Modes
Our next goal is to determine the best display mode available. When compared to the other tasks; it is pretty easy. There are two applicable methods to do this. The first is to simply use what the user is currently using. You can do this with a single call to:

pMode is the return that matters. It's a structure which gives us the resolution, refresh rate, and format the user is using. This method is quick and easy, but not as adaptive to environments as is sometimes needed. The next method is more complex, but more adaptive. You need two functions:

and

GetAdapterModeCount is simple. It takes the adapter and the back buffer format and gives the number of display modes. EnumAdapterModes is a little more complex, but still simple. It also takes the adapter and back buffer format, but it also needs a number and a place to put mode. The number needs to be less than what GetAdapterModeCount returns, and pMode just needs to be some usable memory. You generally use the two in a loop to find the values you want. For example:

This code gets the absolute best display mode for the chosen format and puts it into bestmode.

Initialize
Now that we have all of this data we can initialize our device the way it should be done - fast and flexible! Our first goal is to fill in the D3DPRESENT_PARAMETERS structure. This is where the bulk of our data goes. Here's the structure in all its glory:

And here's how we'll fill it in (in a mostly linear order):

If you noticed, we didn't fill in all of the parameters. That's because we need to know what our application will do - we have (for the most part) free range on the parameters left. Our first unfilled parameter is BackBufferCount. We can fill this with any value between 0 and D3DPRESENT_BACK_BUFFERS_MAX. Generally we want this to be 1. Next we have SwapEffect. A list of valid swap effects can be found here: http://msdn.microsoft.com/en-us/library/bb172612(VS.85).aspx. Generally this is D3DSWAPEFFECT_DISCARD. This MUST be D3DSWAPEFFECT_DISCARD if we set MultiSampleType to anything other than D3DMULTISAMPLE_NONE. Now we need to set EnableAutoDepthStencil. This can be TRUE or FALSE. If we want Direct3D to manage the depth stencil (we do), it should be TRUE. Finally, we need to get a value for Flags. This can be 0 or any of the values listed here: http://msdn.microsoft.com/en-us/library/bb172586(VS.85).aspx. We'll use 0. And here's our code for the rest of the parameters:

Now we can call the CreateDevice function. If you'll recall, it looked like this:

The only parameter that needs explaining is BehaviorFlags. BehaviorFlags specifies many things as a bitmask. A complete list of constants it can include is here: http://msdn.microsoft.com/en-us/library/bb172527(VS.85).aspx. We will just be using it for the type of vertex processing we want. So we just plug in our vtx_proc variable. And this is our final device initialization function!

Cleaning Up
Although not strictly involved in initialization, it is good to talk about freeing up the memory you allocated in the initialization section. All devices created with the Direct3D object as well as the object itself must be released with their Release functions. Here, the only things we allocated were the device and the object, so we need to do: