Creating Your Game Project

Go ahead and load up Visual Studio .NET 2003, and click the New Project button on the start page. If you do not use the start page, click the Project item under the New submenu on the File menu, or use the shortcut Ctrl+Shift+N. Choose the Windows Application item under the Visual C# Projects section.
Name this project Blockers because that is what the name of the game will be.

Before you start looking at the code that was automatically generated, first add the code files for the sample framework into your project. Normally, I put these files into a separate folder by right-clicking on the project in the solution explorer and choosing New Folder from the Add menu. Call this folder Framework. Right-click on the newly created folder and this time choose Add Existing Item from the Add menu. Navigate to the DirectX SDK folder, and you will find the sample framework files in the Samples\Managed\Common folder. Select each of these files to add to your project.
With the sample framework added to the project now, you can get rid of the code that was automatically generated. Most of it is used to make fancy Windows Forms applications, so it's irrelevant to the code you will be writing for this game. Replace the existing code and class (named Form1) with the code in
The Empty Framework
using System;
using System.Configuration;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Microsoft.Samples.DirectX.UtilityToolkit;

public class GameEngine : IDeviceCreation
{
    /// 
    /// Entry point to the program. Initializes everything and goes into a
    /// message processing loop. Idle time is used to render the scene.
    /// 
    static int Main()
    {
        using(Framework sampleFramework = new Framework())
        {
            return sampleFramework.ExitCode;
        }
    }
}

Three things should stand out from this new code. First, you'll notice that everything was removed, with the exception of the static main method, which was modified. The rest of the code was support code for the Windows Form designer.
Because you won't be using that designer for this application, the code isn't relevant and can be removed. Second, this code won't compile because the two interfaces the game engine class is supposed to implement haven't been implemented yet. Third, the code doesn't actually do anything.
Before you begin fixing those last two problems, you'll need to add some references. Because you will be rendering fancy 3D graphics during this project, you probably need to add references to an assembly capable of doing this rendering. This book focuses on using the Managed DirectX assemblies to do this work, so in the Project menu, click Add Reference. It brings up a dialog much like you see in Figure 3.1.
If you have the Summer 2004 SDK update of DirectX 9 installed (which you should because the code in this book requires it), you notice that there might be more than one version of each of the Managed DirectX assemblies. Pick the latest version (marked with version 1.0.2902.0). For this project, you add three different assemblies to your references:
  • Microsoft.DirectX
  • Microsoft.DirectX.Direct3D
  • Microsoft.DirectX.Direct3DX
The root DirectX assembly contains the math structures that help formulate any computations needed for the rendering. The other two assemblies contain the functionality of Direct3D and D3DX, respectively. With the references added, you should look briefly at the using clause you added in Listing 3.1 to make sure that the namespaces referenced as well. This step ensures that you don't have to fully qualify your types. For example, without adding the using clause, to declare a variable for a Direct3D device, you would need to declare it as
Microsoft.DirectX.Direct3D.Device device = null;

The using clauses allow you to eliminate the majority of this typing. (No one wants to type all that stuff for every single variable you would be declaring.) Because you've already added the using clauses, you could instead declare that same device in this way:
private Device device = null;

As you can see, declaring the device in this way is much easier. You've saved yourself an immense amount of typing. With these few things out of the way, now you begin to fix the compilation errors in the application and get ready to write your first 3D game. The only interface you've currently got to implement is IDeviceCreation, which is designed to let you control the enumeration and creation of your device.
You might be thinking, "Enumerating devices? I've only got one monitor!" Although most top-of-the-line, modern graphics cards actually do support multiple monitors (multimon for short), even if you have only a single device, you still have many different modes to choose from. The format of the display can vary. (You might have even seen this variety in your desktop settings on the Windows desktop, as in 16-bit or 32-bit colors.) The width and height of the full-screen modes can have different values, and you can even control the refresh rate of the screen. All in all, there are quite a few things to account for.
To fix the compilation errors in the application, add the code in Listing 3.2.
Listing 3.2. Implementing the Interface
/// 
/// Called during device initialization, this code checks the device for a
/// minimum set of capabilities and rejects those that don't pass by
/// returning false.
/// 
public bool IsDeviceAcceptable(Caps caps, Format adapterFormat,
 Format backBufferFormat, bool windowed)
{
    // Skip back buffer formats that don't support alpha blending
    if (!Manager.CheckDeviceFormat(caps.AdapterOrdinal, caps.DeviceType,
        adapterFormat, Usage.QueryPostPixelShaderBlending,
        ResourceType.Textures, backBufferFormat))
        return false;

    // Skip any device that doesn't support at least a single light
    if (caps.MaxActiveLights == 0)
        return false;

    return true;
}

/// 
/// This callback function is called immediately before a device is created
/// to allow the application to modify the device settings. The supplied
/// settings parameter contains the settings that the framework has selected
/// for the new device, and the application can make any desired changes
/// directly to this structure. Note however that the sample framework
/// will not correct invalid device settings so care must be taken
/// to return valid device settings; otherwise, creating the device will fail.
/// 
public void ModifyDeviceSettings(DeviceSettings settings, Caps caps)
{
    // This application is designed to work on a pure device by not using
    // any get methods, so create a pure device if supported and using HWVP.
    if ( (caps.DeviceCaps.SupportsPureDevice) &&
        ((settings.BehaviorFlags & CreateFlags.HardwareVertexProcessing) != 0 ) )
        settings.BehaviorFlags |= CreateFlags.PureDevice;
}

Look at the first method you declared, the IsDeviceAcceptable method. While the sample framework is busy enumerating the devices on the system, it calls this method for every combination it finds. Notice how the method returns a bool value? This is your opportunity to tell the sample framework whether you consider this device acceptable for your needs. Before you look at the code in that first method, however, notice the second method that's been declared, ModifyDeviceSettings. This method is called by the sample framework immediately before the device is created, allowing you to tweak any options you want. Be careful with the options you choose because you could cause the device creation to fail.
Now, back to that first method: first take a look at the parameters that it accepts. First, it takes a type called Caps, which is short for capabilities. This structure has an amazing amount of information about the particular device that will help you decide whether this is the type of device you want to use. The next two parameters are formats that are specific to the device: one for the back buffer and the other the device's format.
Construction Cue

The back buffer is where the actual rendered data (the pixels) is stored before that data is sent to the video card to be processed and put onscreen. The back buffer formats determine how many colors can be displayed. Most of the formats follow a particular naming convention, each character followed by a number, such as A8R8G8B8. The component specified by the character has a number of bits equal to the number. In A8R8G8B8, the format can contain 32 bits of information for color, with 8 each for alpha, red, green, and blue. The most common components are

A Alpha


R Red


G Green


B Blue


X Unused
You can look in the DirectX SDK documentation for more information on formats.

Because it's also important to know whether this device can render to a window, that is the last parameter to this method. Although the majority of games run in full-screen mode, it can be difficult to write and debug a game running in full-screen mode. During debugging, this application renders in windowed mode rather than full-screen mode.
Construction Cue

Windowed mode is how most of the applications you run are opened. Many of them have a border and the control menu, the minimize and maximize buttons, and a close button in the upper-right corner. In full-screen mode, the application covers the entire screen and in most cases does not have a border. You can change the desktop resolution if the full-screen mode is using a different screen size from your currently running desktop.

You'll notice that the default behavior is to accept the device, but before it is accepted, two specific checks happen. The first check ensures that the device passed in can perform alpha blending (the user interface for the game will require this), and if it cannot, it returns false to signify that this device is not acceptable. Next, the capabilities are checked to see whether there is support for active lights. Scenes with no lighting look flat and fake, so you always want at least a single light.
There's also code that actually modifies the device before creation, and even though you won't be creating the device in this chapter, you'll want to know what this code is for. Devices can do the processing required to render vertices in various ways, by either performing the calculations in hardware, performing them in software, or doing a mixture of both. If the processing happens entirely in hardware, another mode, called a pure hardware device, allows potentially even greater performance. This code checks whether you are currently going to create a hardware processing device; if you are and the pure device is available, it switches to using that instead. The only time you cannot create a pure device (if it is available) is if you are planning to call one of the many get methods or properties on a device. Because you won't be doing that in any of the applications in this book, you're free to use this more powerful device.
There is one last thing to do before you're ready to go on. The sample framework has some unsafe code in it, so you need to update your project to handle it.

Enumerating All Device Options

Now you're ready to have the framework start enumerating the devices on your system. First, declare a constructor for the game engine class, and pass in the sample framework's instance you've created from main. See Listing 3.3.
Listing 3.3. Adding a Constructor
private Framework sampleFramework = null; // Framework for samples
/// Create a new instance of the class
public GameEngine(Framework f)
{
    // Store framework
    sampleFramework = f;
}

The constructor doesn't do anything other than store the sample framework instance because that is required for almost everything that happens within the game. One of the first things the sample framework does after you invoke it is try to enumerate all the devices on your system. In your project file, you'll see a file dxmutenum.cs in the Framework folder you created earlier. This file contains all the necessary code to enumerate the devices on your system. Because it is important that you understand the how and why of the device enumeration, open that file now.
One of the first things you should notice is that the Enumeration class itself cannot be created, and every member variable and method is declared as static. Because it is (at least currently) extremely unlikely that your graphics hardware would change while your application is running (and the computer is on), it is reasonable to have the enumeration code run only once at the beginning of the application.
The bulk of the enumeration works starts from the Enumerate method, which is called by the sample framework before device creation. Notice that the only parameter this method accepts is the interface you've implemented in the game engine class so far. This interface is stored because later, as the device combinations are enumerated, the IsDeviceAcceptable method is called to determine whether the device should be added to the list of valid devices.
So how are the devices actually enumerated? The bulk of the functionality resides in the Manager class from Managed DirectX. If you're familiar with the unmanaged DirectX Application Programming Interface (API), this class mirrors the IDirect3D9 Component Object Model (COM) interface. Notice the first loop in the Enumerate method in Listing 3.4.
Listing 3.4. Enumerating Devices
// Look through every adapter on the system
for each(AdapterInformation ai in Manager.Adapters)
{
    EnumAdapterInformation adapterInfo = new EnumAdapterInformation();
    // Store some information
    adapterInfo.AdapterOrdinal = (uint)ai.Adapter; // Ordinal
    adapterInfo.AdapterInformation = ai.Information; // Information

    // Get list of all display modes on this adapter.
    // Also build a temporary list of all display adapter formats.
    adapterFormatList.Clear();

    // Now check to see which formats are supported
    for(int i = 0; i < allowedFormats.Length; i++)
    {
        // Check each of the supported display modes for this format
        for each(DisplayMode dm in ai.SupportedDisplayModes[allowedFormats[i]])
        {
            if ( (dm.Width < minimumWidth) ||
                (dm.Height < minimumHeight) ||
                (dm.Width > maximumWidth) ||
                (dm.Height > maximumHeight) ||
                (dm.RefreshRate < minimumRefresh) ||
                (dm.RefreshRate > maximumRefresh) )
            {
                continue; // This format isn't valid
            }

            // Add this to the list
            adapterInfo.displayModeList.Add(dm);

            // Add this to the format list if it doesn't already exist
            if (!adapterFormatList.Contains(dm.Format))
            {
                adapterFormatList.Add(dm.Format);
            }
        }
    }

    // Get the adapter display mode
    DisplayMode currentAdapterMode = ai.CurrentDisplayMode;
    // Check to see if this format is in the list
    if (!adapterFormatList.Contains(currentAdapterMode.Format))
    {
        adapterFormatList.Add(currentAdapterMode.Format);
    }

    // Sort the display mode list
    adapterInfo.displayModeList.Sort(sorter);

    // Get information for each device with this adapter
    EnumerateDevices(adapterInfo, adapterFormatList);

    // If there was at least one device on the adapter and it's compatible,
    // add it to the list
    if (adapterInfo.deviceInfoList.Count > 0)
    {
        adapterInformationList.Add(adapterInfo);
    }
}

The Adapters property on the Manager class is a collection that contains information about every "adapter" on your system. The term adapter is somewhat of a misnomer, but the basic definition is anything a monitor can connect to. For example, let's say you have an ATI Radeon 9800 XT graphics card. There is only a single graphics card here, but it is possible to hook up two different monitors to it (via the video graphics adapter [VGA] port and the Digital Visual Interface [DVI] port on the back). With the two monitors hooked up, this single card would have two adapters, and thus two different devices.
Construction Cue

There is a way to have a single card share resources among all "different" devices by creating the device as an adapter group. There are several limitations to this approach. See the DirectX documentation for more information on this topic.

Depending on your system, this loop has at least a single iteration. After storing some basic information about the currently active adapter, the code needs to find all the possible display modes this adapter can support in full-screen mode. You'll notice here that the supported display modes can be enumerated directly from the adapter information you are currently enumerating, and that's exactly what this code is doing.
The first thing that happens when a display mode is enumerated is it's checked against a set of minimum and maximum ranges. Most devices support a wide range of modes that nothing would actually want to render at today. A number of years ago, you might have seen games running in a 320x200 full-screen window, but today it just doesn't happen (unless you happen to be playing on a handheld such as Gameboy Advance). The default minimum size the sample framework picks is a 640x480 window, and the maximum isn't set.
Construction Cue

Just because the sample framework picks a minimum size of 640x480, that doesn't mean in full-screen mode the sample framework will choose the smallest possible size. For full-screen mode, the framework picks the best available size, which is almost always the current size of the desktop (which most likely is not 640x480).

After the supported modes that meet the requirements of the framework are added to the list, the current display mode is then added because it is naturally always supported. Finally, the modes themselves are sorted by an implementation of the IComparer interface. See Listing 3.5.
Listing 3.5. Sorting Display Modes
public class DisplayModeSorter : IComparer
{
    /// 
    /// Compare two display modes
    /// 
    public int Compare(object x, object y)
    {
        DisplayMode d1 = (DisplayMode)x;
        DisplayMode d2 = (DisplayMode)y;

        if (d1.Width > d2.Width)
            return +1;
        if (d1.Width < d2.Width)
            return -1;
        if (d1.Height > d2.Height)
            return +1;
        if (d1.Height < d2.Height)
            return -1;
        if (d1.Format > d2.Format)
            return +1;
        if (d1.Format < d2.Format)
            return -1;
        if (d1.RefreshRate > d2.RefreshRate)
            return +1;
        if (d1.RefreshRate < d2.RefreshRate)
            return -1;

        // They must be the same, return 0
        return 0;
    }
}

The IComparer interface allows a simple, quick sort algorithm to be executed on an array or collection. The only method the interface provides is the Compare method, which should return an integernamely, +1 if the left item is greater than the right, -1 if the left item is less than the right, and 0 if the two items are equal. As you can see with the implementation here, the width of the display mode takes the highest precedence, followed by the height, format, and refresh rate. This order dictates the correct behavior when comparing two modes such as 1280x1024 and 1280x768.
Once the modes are sorted, the EnumerateDevices method is called. You can see this method in Listing 3.6.
Listing 3.6. Enumerating Device Types
private static void EnumerateDevices(EnumAdapterInformation adapterInfo,
    ArrayList adapterFormatList)
{
    // Ignore any exceptions while looking for these device types
    DirectXException.IgnoreExceptions();
    // Enumerate each Direct3D device type
    for(uint i = 0; i < deviceTypeArray.Length; i++)
    {
        // Create a new device information object
        EnumDeviceInformation deviceInfo = new EnumDeviceInformation();

        // Store the type
        deviceInfo.DeviceType = deviceTypeArray[i];

        // Try to get the capabilities
        deviceInfo.Caps = Manager.GetDeviceCaps(
            (int)adapterInfo.AdapterOrdinal, deviceInfo.DeviceType);

        // Get information about each device combination on this device
        EnumerateDeviceCombos( adapterInfo, deviceInfo, adapterFormatList);

        // Do we have any device combinations?
        if (deviceInfo.deviceSettingsList.Count > 0)
        {
            // Yes, add it
            adapterInfo.deviceInfoList.Add(deviceInfo);
        }
    }
    // Turn exception handling back on
    DirectXException.EnableExceptions();
}

When looking at this code, you should notice and remember two very important things. Can you guess what they are? If you guessed the calls into the DirectXException class, you win the grand prize. The first one turns off exception throwing in virtually all cases from inside the Managed DirectX assemblies. You might wonder what benefit that would give you, and the answer is performance. Catching and throwing exceptions can be an expensive operation, and this particular code section could have numerous items that normally throw these exceptions. You would expect the enumeration code to execute quickly, so any exceptions that occur are simply ignored, and after the function finishes, normal exception handling is restored. The code itself seems pretty simple, though, so you're probably asking, "Why would this code be prone to throwing exceptions anyway?"
Well, I'm glad you asked, and luckily I just happen to have a good answer. The most common scenario is that the device doesn't support DirectX 9. Maybe you haven't upgraded your video driver and the current video driver doesn't have the necessary code paths. It could be that the card itself is simply too old and incapable of using DirectX 9. Many times, someone enables multimon on his system by including an old peripheral component interconnect (PCI) video card that does not support DirectX 9.
The code in this method tries to get the capabilities and enumerate the various combinations for this adapter, and it tries to get this information for every device type available. The possible device types follow:
  • Hardware The most common device type created. The rendering is processed by a piece of hardware (a video card).
  • Reference A device that can render with any settings supported by the Direct3D runtime, regardless of whether there is a piece of hardware capable of the processing. All processing happens in software, which means this device type is much too slow in a game.
  • Software Unless you've written a software rasterizer (in which case, you're probably beyond this beginners' book), you will never use this option.
Assuming some combination of device settings was found during the enumeration, it is stored in a list. The enumeration class stores a few lists that the sample framework uses later while creating the device. See Listing 3.7 for the EnumerateDeviceCombos method.
Listing 3.7. Enumerating Device Combinations
private static void EnumerateDeviceCombos(EnumAdapterInformation adapterInfo,
   EnumDeviceInformation deviceInfo, ArrayList adapterFormatList)
{
    // Find out which adapter formats are supported by this device
    for each(Format adapterFormat in adapterFormatList)
    {
        for(int i = 0; i < backbufferFormatsArray.Length; i++)
        {
            // Go through each windowed mode
            bool windowed = false;
            do
            {
                if ((!windowed) && (adapterInfo.displayModeList.Count == 0))
                    continue; // Nothing here

                if (!Manager.CheckDeviceType((int)adapterInfo.AdapterOrdinal,
                    deviceInfo.DeviceType,  adapterFormat,
                    backbufferFormatsArray[i], windowed))
                       continue; // Unsupported

                // Do we require post pixel shader blending?
                if (isPostPixelShaderBlendingRequired)
                {
                    if (!Manager.CheckDeviceFormat(
                            (int)adapterInfo.AdapterOrdinal,
                            deviceInfo.DeviceType, adapterFormat,
                            Usage.QueryPostPixelShaderBlending,
                            ResourceType.Textures, backbufferFormatsArray[i]))
                        continue; // Unsupported
                }

                // If an application callback function has been provided,
                // make sure this device is acceptable to the app.
                if (deviceCreationInterface != null)
                {
                    if (!deviceCreationInterface.IsDeviceAcceptable(deviceInfo.Caps,
                        adapterFormat, backbufferFormatsArray[i],windowed))
                        continue; // Application doesn't like this device
                }

                // At this point, we have an adapter/device/adapterformat/
                // backbufferformat/iswindowed DeviceCombo that is supported
                // by the system and acceptable to the app. We still need
                // to find one or more suitable depth/stencil buffer format,
                // multisample type, and present interval.

                EnumDeviceSettingsCombo deviceCombo = new
                 EnumDeviceSettingsCombo();

                // Store the information
                deviceCombo.AdapterOrdinal = adapterInfo.AdapterOrdinal;
                deviceCombo.DeviceType = deviceInfo.DeviceType;
                deviceCombo.AdapterFormat = adapterFormat;
                deviceCombo.BackBufferFormat = backbufferFormatsArray[i];
                deviceCombo.IsWindowed = windowed;

                // Build the depth stencil format and multisample type list
                BuildDepthStencilFormatList(deviceCombo);
                BuildMultiSampleTypeList(deviceCombo);
                if (deviceCombo.multiSampleTypeList.Count == 0)
                {
                    // Nothing to do
                    continue;
                }
                // Build the conflict and present lists
                BuildConflictList(deviceCombo);
                BuildPresentIntervalList(deviceInfo, deviceCombo);

                deviceCombo.adapterInformation = adapterInfo;
                deviceCombo.deviceInformation = deviceInfo;

                // Add the combo to the list of devices
                deviceInfo.deviceSettingsList.Add(deviceCombo);
                // Flip value so it loops
                windowed = !windowed;
            }
            while (windowed);
        }
    }
}

Much like earlier methods, this one goes through a list of items (in this case, formats) and creates a new list of valid data. The important item to take away from this method is the call into the IsDeviceAcceptable method. Notice that if false is returned from this method, the device combination is ignored.

Comments

Popular Posts