Managed DirectX First Steps: Direct3D

Một phần của tài liệu net game programming with directx 9.0 (2003) (Trang 127 - 200)

Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen

Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay

Chapter 9 -D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code

Bonus Chapter Porting .Nettrix to Pocket PC Appendix A- The State of PC Gaming Appendix B- Motivations in Games Appendix C- How Do I Make Games?

Appendix D- Guidelines for Developing Successful Games Index

List of Figures List of Tables

Chapter 3: Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+

Highlights

In this chapter we'll follow a different approach from all the other ones: There'll be no sample game, and we'll instead concentrate on understanding the basic features of DirectX (particularly Direct3D) and how to go through its initialization routines, creating a sample application that will exemplify each of these

features.

Our sample application, as we'll see in the section "The Application Proposal," will comprise a main window, which will display our 3-D board capabilities, and a set of separate windows that will test a specific feature each, like use of lights, 3-D transformations, and full-screen drawings. In each of these test windows we'll present sequentially the drawings of a walking man, shown in Figure 3-1, providing the illusion of movement.

Figure 3-1: The walking man, presented as this chapter's sample

DirectX is a set of libraries and components that allow the programmer to access hardware features (such as 3-D acceleration boards and advanced sound systems) using the same interface, disregarding the device details, while still taking advantage of each hardware-specific feature to enhance the multimedia operation speed.

The latest version of DirectX can be downloaded from http://www.microsoft.com/directx; this download includes the DirectX APIs, the managed DirectX interfaces (used to provide access to DirectX from .NET languages), the DirectX Software Development Kit (SDK), a comprehensive set of samples, and detailed documentation about all DirectX features.

In the next section we'll present an overview of DirectX, which will give us enough information to go on exploring Direct3D features in the later sections.

.NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen

Hatton

ISBN:1590590511

Apress © 2003 (696 pages)

The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio.

Table of Contents

.NET Game Programming with DirectX 9.0 Foreword

Preface Introduction

Chapter 1 - .Nettrix: GDI+ and Collision Detection

Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites

Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+

Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen

Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay

Chapter 9 -D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code

Bonus Chapter Porting .Nettrix to Pocket PC Appendix A- The State of PC Gaming Appendix B- Motivations in Games Appendix C- How Do I Make Games?

Appendix D- Guidelines for Developing Successful Games Index

List of Figures List of Tables

DirectX Overview

In this section we'll discuss some common terms used in the DirectX world and see how they fit together to provide us a framework for building great games.

First of all, those who already know previous versions (7 or earlier) of DirectX need to be aware that since DirectX 8 we no longer have direct support for 2-D games. That means there is no capability for screen flipping and no bitmap blitting directly on video memory. We don't have the DirectDraw interface anymore, which was very comfortable to those who programmed DOS games, because it used much of a familiar, basic philosophy:

Create one or more screen back buffers, draw in a back buffer, move the back buffer to video memory—in other words, make it visible to the player—and then start drawing in the next buffer (usually, we simply "flip" the buffers, moving memory pointers).

In fact, the DirectDraw interface is still there, but it's for now just a backward-compatibility feature, so the old programs that use this library will still work. It's better for us not to rely on the older interface because no one knows if it will be present in the next versions.

The good news is that, while we need to expend a little more effort in Direct3D than in DirectDraw, we can rely on the hardware acceleration capabilities to do most of the dirty work for us, reaching incredible speeds that would not be possible with DirectDraw.

Using hardware acceleration is a wonderful thing, because we can go from dozens of frames to hundreds of frames drawn per second. In our tests in this chapter, the basic samples easily reach three hundred frames per second, and can go to almost a thousand depending on the hardware capabilities.

Of course, there's a price to pay. Even the simplest games must go through some complex routines, and we'll have to learn some new concepts, even if we don't want to take full advantage of the hardware acceleration features.

When we manage to understand these initialization routines and the basic concepts, we can use the Direct3D interface to create our 2-D games without even worrying about depth buffers or vertex blending.

Let's start with an overview of the main concepts used by DirectX and how they are related.

Presenting the DirectX Top-Level Objects

When programming DirectX 9.0 or earlier with nonmanaged (pre-.NET) languages, we have to create a master object of type DirectXn (where n is the main number of the DirectX version, for instance, DirectX8 for the 8.1 version), and everything can be created from this object.

In the managed version of DirectX 9.0, we can directly create the second-level objects, as listed here:

Direct3D for access to the 3-D acceleration layer.

Direct3DX for access to utility functions to make coding easier (such as matrix multiplication functions).

DirectDraw for compatibility with older programs, although there are no new features for this component.

It's mainly used to create 2-D games, because it allows access to a hardware blittler (hardware acceleration to allow fast transfer of large memory blocks) and creation on drawing surfaces easily.

DirectInput for controlling any input devices, including newer ones, like joysticks with force feedback.

DirectPlay for creating multiplayer games, creating fast and reliable data transmission across computers.

It's based mainly in TCP sockets, but has some game-related extra features.

DirectAudio for manipulating and playing all kinds of sounds. It includes the DirectSound and

DirectMusic interfaces from previous releases, and, in fact, it's not a new interface, just a new way to call the other two when used together. Although both DirectSound and DirectMusic are present in DirectX 9.0, only DirectSound has a managed interface.

.NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen

Hatton

ISBN:1590590511

Apress © 2003 (696 pages)

The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio.

Table of Contents

.NET Game Programming with DirectX 9.0 Foreword

Preface Introduction

Chapter 1 - .Nettrix: GDI+ and Collision Detection

Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites

Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+

Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen

Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay

Chapter 9 -D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code

Bonus Chapter Porting .Nettrix to Pocket PC Appendix A- The State of PC Gaming Appendix B- Motivations in Games Appendix C- How Do I Make Games?

Appendix D- Guidelines for Developing Successful Games Index

List of Figures List of Tables

DirectShow for video and audio playback or capture. In DirectX 9.0, we have only a simple playback feature in DirectShow; if we need to use advanced streaming manipulation features, we have to use the nonmanaged version.

DirectSetup for access to the setup API of DirectX, which can help with creating distribution packages for DirectX-based applications.

In this chapter we'll concentrate in the first object listed, Direct3D, and learn some helper functions from Direct3DX. In upcoming chapters, we'll examine the other objects one by one, with the exception of the outdated DirectDraw and the DirectSetup interface.

Understanding Adapters

This section relates directly to video hardware. DirectX provides some functions that allow us to list all display adapters and gather some information about them.

We don't do any direct operations over an adapter; the functions are here just for informational purposes, or to allow us to choose between adapters when we have more than one acceleration board.

Usually we'll have only one adapter (the default), but with machines with secondary adapters (such as 3-D-only boards), we can use the adapter identifier (a sequential number) to switch from one adapter to another.

To gather the adapter information, we can use the following code sample:

Dim AdapterInfo As AdapterDetail Dim i As Integer

For i = 0 To Manager.Adapters.Count - 1

AdapterInfo = Manager.Adapters(i).Information

messageBox.show (AdapterInfo.Description, "Current Adapters") Next i

In managed DirectX, many of the methods were reengineered to provide a more intuitive interface. For example, many Get methods were replaced by properties, such as the Adapters.Count property in the preceding code, which replaced the previous GetAdapterCount property. Some functions that return values as parameters were also rewritten to return values as the result of the function. There's also a new object, the Manager, presented in the previous code sample, that handle basic interactions with Direct3D. This kind of modifications made the code cleaner for the managed version of DirectX.

The code listing uses the Adapters.Count property to run across the adapters and gather the description of each one. Although Description can vary for the same device and driver when dealing with different vendors, it's the only human-readable information, along with the DriverName property of the

AdapterDetail structure. The other members of this structure are numeric values that identify the driver version, revision, and other internal control numbers, and won't be of interest to us (refer to DirectX SDK help for further information).

Understanding Devices

DirectX offers a special object type, Device, which allows us to have access to the 3-D acceleration layer. We can choose up to three types of devices for each adapter:

Hardware (Hardware Abstraction Layer): When creating HAL devices, we have direct access to the hardware acceleration features (and increased speed). If we try to create a device of this type but have no 3-D acceleration board, DirectX will raise an error and won't create the device.

Reference (Reference Rasterizer): This type of device, included in the DirectX SDK, provides most of the

.NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen

Hatton

ISBN:1590590511

Apress © 2003 (696 pages)

The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio.

Table of Contents

.NET Game Programming with DirectX 9.0 Foreword

Preface Introduction

Chapter 1 - .Nettrix: GDI+ and Collision Detection

Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites

Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+

Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen

Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay

Chapter 9 -D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code

Bonus Chapter Porting .Nettrix to Pocket PC Appendix A- The State of PC Gaming Appendix B- Motivations in Games Appendix C- How Do I Make Games?

Appendix D- Guidelines for Developing Successful Games Index

List of Figures List of Tables

features available for the DirectX functions, and doesn't depend on any hardware support—everything is made by software. Although this type of device is very flexible, it's very slow, and must only be used for debugging purposes, because it allows us to test many features not supported by our hardware. Don't even think about creating a game with it, as the frame rate is very low—between 1 and 5 frames per second, usually.

Software (Software Device): Not used, unless you need plug-in support for creating a custom renderer.

When creating a device, we must specify the adapter being used (usually the default, defined as "0" [zero]), the type of the device as described in the preceding list, the handle of the window that will be used as a viewport, and two other parameters that will define the details about the device creation, the behavior flags and the presentation parameters, as shown in the next code sample:

objDirect3DDevice = New Device(Manager.Adapters.Default.Adapter, _

DeviceType.hardware, WinHandle, CreateFlags.SoftwareVertexProcessing, _ objDirect3Dpp)

The behavior flags must be one of the following flags defined by the CreateFlags enumeration:

SoftwareVertexProcessing: The most common option, it tells DirectX that all vertex calculations will be made by software. This option is the slowest, but is always available.

HardwareVertexProcessing: This option forces DirectX to rely on hardware capabilities to make all the vertex-processing operations, leaving extended operations (like shading and lighting) for the software layer.

If the hardware is not able to perform the vertices calculation, the creation of the device will fail.

MixedVertexProcessing: As the constant name states, this uses a mix of available hardware features and software-implemented ones to achieve the best results. If the hardware offers no vertex-processing features, this call will fail, too.

These flags are mutually exclusive, but they can be combined with the following flags to pass additional information to DirectX when creating a device:

FPU_Preserve: This flag informs DirectX to perform all the calculations using double-precision floating points, which can lead to slower performance.

MultiThreaded: Use this flag to inform DirectX that you need a multithread safe environment. In order to control the critical sections, DirectX can lose performance, so you must use this flag only when needed.

PureDevice: This flag is used only in combination with the HardwareVertexProcessing flag, and specifies that the hardware can do rasterization, matrix transformations, and lighting and shading calculations. It's the best choice for any application, but few boards offer these features.

The last parameter for creating a device, the Presentation Parameters, is a complex structure whereby the programmer can define many low-level details about the device being created. We'll present here the most commonly used attributes. For a full list refer to the DirectX SDK help feature.

EnableAutoDepthStencil and AutoDepthStencilFormat: These structure members tell DirectX that you want to use a depth buffer, and which is the format to be used in such buffer (according to the Format enumeration), respectively. The depth buffer helps with defining the relative distance of the object in relation to the screen, which is used to draw nearby objects in front of far ones. Although this seems to be a concept exclusive to the 3-D gaming world, it's not entirely true: Even some very basic 2-D games have so- called layers—usually the background and any objects that must appear behind the player (such as trees or bushes) stay in a back layer, and the player and other objects stay in the front layers. After creating the device, the program must set the ZBufferEnable member of the device's RenderState component to enable the depth buffering.

BackBufferCount, BackBufferFormat, BackBufferWidth, and BackBufferHeight: These

.NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen

Hatton

ISBN:1590590511

Apress © 2003 (696 pages)

The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio.

Table of Contents

.NET Game Programming with DirectX 9.0 Foreword

Preface Introduction

Chapter 1 - .Nettrix: GDI+ and Collision Detection

Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites

Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+

Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen

Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay

Chapter 9 -D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code

Bonus Chapter Porting .Nettrix to Pocket PC Appendix A- The State of PC Gaming Appendix B- Motivations in Games Appendix C- How Do I Make Games?

Appendix D- Guidelines for Developing Successful Games Index

List of Figures List of Tables

members define the number of back buffers (from 1 to 3), the format of such buffers (defined by the Format enumeration), and their width and height. The back buffer format (as with the depth stencil buffer) must be valid, one that can be checked by the CheckDeviceType method of the Direct3D object. If the buffer cannot be created (at least one is required), the creation of the Device will fail. The back buffers are used to render the scene being draw in the background automatically, in order to allow a smooth transition between frames drawn (no partial drawing is shown to the player). This parameter is closely related to the SwapEffect attribute, which will tell DirectX how to swap the back buffers to the screen, and to the Windowed attribute, which will force some limitations to the possible values.

SwapEffect: A constant of the SwapEffect enumeration that defines the behavior of the buffers swap operation. This enumeration includes the following options:

SwapEffect.Discard: The back buffers content isn't preserved in the swap operation, allowing the application to choose the best performing technique, sometimes leading to big performance gains in the swapping operation. However, the scene must be completely redrawn for each frame.

SwapEffect.Flip: Creates a circular list of buffers to be swapped to screen (called a swap chain), allowing synchronization with the video refresh rate in a smooth way when running full screen. The

"flip" term means that we have no copy of the memory block—DirectX just repositions the video memory start pointer to the next buffer. When running in windowed mode, there's no real flip; the video memory gets copied to the window, which is an operation with slower performance. In this operation, the front buffer becomes one of the back buffers, so the game can rely on this to redraw only part of the scene.

SwapEffect.Copy: This setting preserves the contents of the back buffer, just copying it over the front buffer (the screen). This setting forces BackBufferCount to be set to 1, since there's no need to more buffers. This is the most simple of the buffer swap operations, although it's the one with the worst performance. The most important gain for the programmer is that the application is not forced to perform complex control operations over multiple back buffers.

Windowed: When set to True, indicates that the application will run in a window; a setting of False indicates the application will run full screen. When running in windowed mode, BackBufferFormat must match the current display resolution, and BackBufferWidth and BackBufferHeight may not be specified, assuming the window client area dimensions. When running in full screen, the width and height of the back buffer must match one of the possible display modes (explained in the next section) for the device.

DeviceWindowHandle: The handle of the window to be used by DirectX. If it's set to Nothing, DirectX will use the active window.

Understanding Display Modes

While the term adapter refers to the hardware and its driver and the term device refers to the main object used to access a specific window and draw over it, we use the term display modes to define the objects (the

DisplayMode class) that store basic information about the screen status, including width, height, refresh rate, and a format flag that returns extra information about how colors are controlled by the display. The formats for rendering displays are as follows:

A8R8G8B8: Color format in which each pixel on screen is defined using a 32-bit ARGB value—255 possible values for each red, green, and blue (RGB) color component, and an extra alpha (A) value that defines the transparency of each pixel (255 is fully opaque and is 0 is totally transparent).

X8R8G8B8: Color format with 32-bit RGB values, and an extra byte (indicated by the "X") for color definition, not used. As with the previous setting, this color format allows up to 16 million colors.

R5G6B5: Color format using 16 bits, where each RGB color component can assume 32 different values; an extra bit for green make this show 64 possible values, reaching a total of about 64 thousand colors.

X1R5G5B5: 16-bit color format in which each color component takes 5 bits (32 possible values), making a

Một phần của tài liệu net game programming with directx 9.0 (2003) (Trang 127 - 200)

Tải bản đầy đủ (PDF)

(573 trang)