The What, Why, and Howof DirectX Prior to DirectX, game makers were struggling with problems stemming fromhardware incompatibilities, making it almost impossible for everyone to enjoythe
Trang 2R
11 Game Programming
Allen Sherrod and Wendy Jones
Course Technology PTR
A part of Cengage Learning
Australia Brazil .Japan.Korea.Mexico.Singapore.Spain.United Kingdom.United States
Trang 3Course Technology PTR: Stacy L Hiquet
Associate Director of Marketing:
Sarah Panella
Manager of Editorial Services:
Heather Talbot
Marketing Manager: Jordan Castellani
Senior Acquisitions Editor: Emi Smith
Project Editor: Dan Foster, Scribe Tribe
Technical Reviewer: Wendy Jones
Interior Layout Tech: MPS Limited,
a Macmillan Company
Cover Designer: Mike Tanamachi
Indexer: Valerie Haynes Perry
Proofreader: Gene Redding
by any means graphic, electronic, or mechanical, including but not limited to photocopying, recording, scanning, digitizing, taping, Web distribution, information networks, or information storage and retrieval systems, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the publisher.
For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, 1-800-354-9706
For permission to use material from this text or product,
submit all requests online at www.cengage.com/permissions
Further permissions questions can be emailed to
Course Technology, a part of Cengage Learning
20 Channel Center Street Boston, MA 02210 USA
Cengage Learning is a leading provider of customized learning solutions with office locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan Locate your local office at:
Trang 4I would like to thank the men and women at Cengage Learning who helped makethis book possible I would also like to thank Wendy Jones for all her hard work
on the previous editions of the book And I would like to give a special thanks toEmi Smith, who has been very patient and helpful with this whole process
Trang 5Allen Sherrodis an experienced author in thefield of video game development.Allen’s past works include two editions of Ultimate Game Programming withDirectX, Ultimate 3D Game Engine Design and Architecture, Game GraphicsProgramming, and Data Structures and Algorithms for Game Developers Allenhas also contributed to Game Developer magazine, the Game ProgrammingGems 6 book, and the Gamasutra.com website Allen is the creator of www.UltimateGameProgramming.com.
Wendy Jonesis co-founder and CTO of Kitty Code LLC, a games studio working
on mobile and console platforms such as iPhone, Windows Phone 7, and theXbox 360 Wendy’s past experience includes working on PC, console, and mobilegame titles while working with Atari and Electronic Arts Wendy also teachesDirectX at Full Sail University and is department chair of the interactivedevelopment department Wendy can be reached through her website at www.fasterkittycodecode.com
Trang 6Introduction xi
Chapter 1 The What, Why, and How of DirectX 1
What Is DirectX? 1
DirectX 10 versus DirectX 9 2
DirectX 11 versus DirectX 10 4
DirectX 11 versus OpenGL 4.0 5
Why Is DirectX Needed? 6
How DirectX Is Put Together 7
The Components of DirectX 11 7
Obsolete DirectX Components 10
Introducing Direct3D 11 12
Stages of Direct3D 11 12
Direct3D 11 Considerations 15
DirectX Tools 16
Sample Browser and Documentation 16
PIX 16
Caps Viewer 17
Diagnostic Tools 17
Texture Tool 18
Error Lookup 19
Control Panel 20
Cross-Platform Audio Creation Tool 20
C o n t e n t s
v
Trang 7Game Definition File Editor 20
Down-Level Hardware 21
Summary 23
Chapter Questions 23
Chapter 2 Your First DirectX Program 27
Creating the Project 27
Adding Windows Code 29
The Main Entry Point 30
Windows Initialization 32
Windows Callback Procedure 42
Time for Direct3D 44
Adding the DirectX Libraries 45
Initializing Direct3D 47
Driver Types and Features Levels 47
Device and Swap Chain Creation 49
Render Target View Creation 53
The Viewport 55
Clearing and Displaying the Screen 56
Cleaning Up 58
Formats 58
The Blank D3D Window 59
Design of the Template Framework 60
The Direct3D Class 60
The Blank Window Demo Class 67
Updating the Application Loop 70
DirectX Error Handling Library 73
Error Handling Functions 73
Error Handling Macros 75
Summary 75
Chapter Questions 76
Chapter 3 2D Rendering 79
2D Game Development 80
Textures 81
Sprites 84
2D Geometry 86
What Is a Vertex? 87
Definition of a Triangle 91
Trang 8Vertex Buffers 94
Input Layout 97
Drawing a 2D Triangle 105
2D Triangle Demo 108
Loading the Geometry 108
Rendering the Geometry 114
Texture Mapping 116
Texture Interfaces 118
MIP Maps 119
Texture Details 121
Texture Mapping Demo 122
Sprites 133
Z-Ordering 134
Sprite Image 135
Getting Sprites to the Screen 136
Positioning and Scaling Sprites 139
The Game Sprite Demo 140
Creating and Rendering the Game Sprite 143
Summary 153
What You Have Learned 153
Chapter Questions 153
On Your Own 154
Chapter 4 Text and Font Rendering 155
Text in Games 155
Adding Text 158
Textured Fonts 159
A Font System Explained 160
Creating a Font System Using Sprites 161
Advanced Topics 171
In-Game Text Boxes 172
In-Game Console Window 172
Game Menus 173
Heads-Up Display 174
Summary 174
Chapter Questions 174
On Your Own 176
Contents vii
Trang 9Chapter 5 Input Detection and Response 177
I Need Input 177
Input Options 179
Keyboard Input 180
Win32 Keyboard Input 180
DirectInput Keyboard Input 183
DirectInput Keyboard Demo 198
Mouse Input 208
DirectInput Mouse Input 209
XInput—Game Controllers 215
Setting Up XInput 216
Controller Vibrations 217
XInput for Input 218
Controller Capabilities 218
Battery Life 219
Keystrokes 220
Headset Sound 221
XInput Demo 222
Summary 225
What You Have Learned 225
Chapter Questions 226
On Your Own 226
Chapter 6 3D Primer 227
XNA Math 228
Utilities 228
Points 229
Vectors 229
Vector Arithmetic 233
Distance Between Vectors 234
Determining the Length of a Vector 235
Normalize a Vector 236
Cross Product 237
Dot Product 237
3D Space 239
Coordinate Systems 239
Transformations 241
World Transformations 242
Trang 10View Transformations 243
Projection Transformations 243
Transforming an Object 244
Matrices 246
The Identity Matrix 247
Matrix Scaling 248
Matrix Translation 249
Matrix Rotation 249
Matrix Concatenation 252
Cube Demo 253
Additional XNA Math Topics 269
Compiler Directives 269
Constants 270
Macros 272
Structures and Types 274
Additional Functions 279
Additional Math Structures and Topics 283
Game Physics and Collision Detection 283
Summary 284
What You Have Learned 284
Chapter Questions 285
Chapter 7 Shaders and Effects 287
Shaders in Direct3D 287
History of Programmable Shaders 288
Effect Files 289
Effect File Layout 290
Loading an Effect File 291
External Variables and Constant Buffers 292
Input and Output Structures 293
Technique Blocks 294
Rasterizer States 296
High Level Shading Language 298
Variable Types 298
Semantics 299
Function Declarations 299
Vertex Shaders 300
Contents ix
Trang 11Pixel Shaders 301
Texture Color Inversion 301
Color Shifting 309
Multitexturing 311
Geometry Shaders 314
Geometry Shader Function Declaration 316
The Geometry Shader Explained 316
Introduction to Lighting 317
Summary 325
What You Have Learned 325
Chapter Questions 325
On Your Own 326
Chapter 8 Cameras and Models in Direct3D 327
Cameras in Direct3D 327
Look-At Camera Demo 328
Arc-Ball Camera Demo 334
Meshes and Models 342
The OBJ File Format 342
Reading Tokens from a File 344
Loading Meshes from OBJ Files 349
Advanced Topics 356
Complex Cameras 357
3D Level Files 360
Summary 363
What You Have Learned 363
Chapter Questions 363
Index 365
Trang 12Many of us wish to create our own video games For some, gaming is a hobby, andfor others it is something fun to participate in casually But for the rest of us,gaming and the dream of making our own games is more like a passion Chancesare, if you’ve purchased this book, you are looking to turn your desire and passioninto something you can play and share with others.
About This Book
This book is the follow-up edition to Wendy Jones’s Beginning DirectX 10 GameProgramming book In this book, we teach you the basics of getting started withgame graphics using the latest iteration of Direct3D: Direct3D 11
The goal of this book is to teach you the various aspects of DirectX 11 The targetaudience for this text is beginning/intermediate C++ programmers with little to
no experience with DirectX Although past DirectX or OpenGL experience can beuseful, it is not required
When you reach the end of this book, you will have had enough experience withDirectX 11 that you should be able to explore making simple video games and demos.Ideally, you will work your way up to make complex games and demos until youfindyourself able to complete and release (even if for free atfirst) your own PC games
Recommended Knowledge
This book assumes you have knowledge and familiarity of the C++ programminglanguage You are also assumed to have a comfortable working knowledge ofVisual Studio 2010 and have completed at least a high-school level of mathe-
I n t r o d u c t i o n
xi
Trang 13matics Since this book is centered on learning DirectX for thefirst time, knowingDirectX is, of course, not required for working through this book.
Throughout this book we use Visual Studio C++ 2010 Express, which can bedownloaded from Microsoft’s website at www.microsoft.com/express/Down-loads We are also using the June 2010 DirectX SDK, which can be downloadedfrom http://msdn.microsoft.com/en-us/directx
Although not required for this book, it is recommended to try Adobe Photoshopfor the creation of textures (www.adobe.com/products/photoshop/photo-shopextended/) and XSI Mod Tool 7.5 for the creation of 3D models and meshes(http://usa.autodesk.com)
Companion Website: Code and Bonus Content
Almost every chapter has code samples and demos that give you hands-onexercises of the topics discussed To follow along, view, execute, or manipulatethese code samples, you will need the book’s accompanying code, which can bedownloaded from:
Errata
Sometimes there are errors that are not caught before the book is released or thatcan even arise due to outside circumstances that we could not anticipate If youfind any errors or issues with the book, please be sure to submit them to thecompanion website at www.ultimategameprogramming.com/BeginningDX11.Also be sure to check the companion website to see if there are existing issues thatother readers have found that you mightfind useful to know
Companion Website Downloads
downloads Please note that you will be redirected to our Cengage Learning site
Trang 14The What, Why, and How
of DirectX
Prior to DirectX, game makers were struggling with problems stemming fromhardware incompatibilities, making it almost impossible for everyone to enjoythe same games due to the sheer volume of hardware configurations that existed
As the industry faced the need for standardization, Microsoft introduced theWindows Game SDK for Windows 95, which became DirectX 1 DirectXprovided game makers with a single set of APIs that would almost guaranteecompatibility across different sets of PC hardware Since DirectX’s release, thenumber of games running under Windows has increased dramatically This isstill true almost 15 years later
In this chapter:
n Understanding what DirectX is
n Why DirectX is useful
n How data flows through the Direct3D 11 pipeline
n What’s new for Direct3D 11
What Is DirectX?
DirectX, Microsoft’s collection of application programming interfaces (APIs), isdesigned to give developers a low-level interface to the PC hardware runningWindows-based operating systems Each component provides access to different
Chapter 1
1
Trang 15aspects of the hardware, including graphics, sound, GPU general purposecomputing, and input devices, all through a standard interface.
This ideology allows developers to write their games using standard APIswithout having to worry about the low-level interfacing with the different pieces
of hardware a customer might have Imagine the difficulty developers once faced
by trying to write code paths for the many different hardware configurations aplayer might have What if the player had a different input device? What about a
between DOS and Windows 95? What about audio hardware and drivers?What about different types and models of graphics hardware?
Having one standard API that hardware manufacturers must adhere to is muchmore ideal than writing code paths for every possible device on the market,especially since newer devices released after a game has shipped could possiblynot be recognized by the game, whereas using a standard solves this issue.DirectX is a collection of APIs used primarily by video game developers toaddress this need for standardization on the Windows and Xbox platforms It is
up to the hardware manufacturers to provide the driver layer for their devices
N o t e
The Xbox 360 uses a variation of DirectX 9.
DirectX 10 versus DirectX 9
In 2006, DirectX 10 presented a major leap forward in the DirectX SDK Usuallywhen discussing DirectX we are discussing Direct3D, which is the API withinDirectX that receives the most overhauls Most other APIs in DirectX are eitherdeprecated (meaning they are up for removal and it’s recommended that newsoftware not use them), are the same or have minor changes, or have beenremoved completely from the SDK
The Direct3D 10 API is very lightweight when compared to its predecessors, andthe API is much easier to use than past versions In fact, early versions ofDirectX were notoriously difficult to learn and use, but Microsoft has madechanges and improvements to the API over many years Direct3D 10 was notjust an upgrade but, in many respects, an API that started fresh And it indeedfelt like a fresh start with the launch of Windows Vista, DirectX 10-class
Trang 16hardware, and a powerful API that was being hyped by one of the most
influential software giants in the world
The most apparent removal in Direct3D 10 was the fixed-function pipeline,
which is essentially a set of rendering states and algorithms built into the API
that allowed for the rendering of objects using common effects The
fixed-function pipeline was removed in favor of programmable shaders within
graphics hardware Graphics shaders, which will be discussed throughout this
book, are code written specifically to customize how the graphics hardware
processes geometry Graphics shaders were first introduced in DirectX 8, but
since then graphics hardware and the Shader Models that they run have evolved
to a point where they have become the star of the API
In Direct3D 9 we can render geometry, enable lighting by setting a few
properties and rendering states, have the API transform our geometry, and so
forth by calling a few Direct3D function calls In Direct3D 10 we can do all of
that ourselves and much more in shaders The key thing for beginners to keep in
mind if this is their first time learning graphics programming is that the
fixed-function pipeline was limited to whatever was built into the API, whereas
shaders allow us to create any effect, limited only by the frame-rate we deem
desirable in our games Want lighting? Call a Direct3D function to enable it and
set its properties (up to eight lights) Want to render surfaces with more than
one image? Just enable it If, however, you wish to perform pixel-based motion
blur and depth-of-field, you are out of luck using the fixed-function pipeline
Often if the fixed-function pipeline does not explicitly support it and you are not
using shaders, you cannot create the effect you want Although some coders
have found tricks and workarounds to getting some effects created without
shaders, it was often a very difficult and inefficient workaround I remember
these times well and do not miss them
Today, if we want to perform bump mapping, we can write a pixel shader that
takes the light direction, performs a calculation using it and the pixel-level
surface direction loaded from a special image known as a normal map, and
combine that with the shading of the final pixel’s color In the days before
shaders, or even when shaders were limited in the features they provided (such
as the dark ages of register combiners for early versions of OpenGL), this was
impossible, and doing even simple effects like normal mapping back then was
What Is DirectX? 3
Trang 17only made possible through inefficient and often poor-quality tricks andapproximations Of course what is considered an easy effect to one persondepends on his experience level.
The leap from DirectX 9 to DirectX 10 was a huge one DirectX 10 went throughtwo iterations as the market’s acceptance caught up
DirectX 11 versus DirectX 10
Direct3D 11 builds upon Direct3D 10.1 to add a new set of features forrendering next-generation graphics The new additions to DirectX 11 includethe following:
n True multi threaded rendering support
n New hardware tessellation
n Shader Model 5.0 and object-oriented programming concepts for shaders
and LDR images, respectively
n Increased texture resolution sizes
widespread, but also the majority of Windows users now are spanning WindowsVista and Windows 7 DirectX has always taken the future into consideration,and with the number of years it takes next-generation games to be developed,DirectX 11 will be very important to gaming for many years to come
Trang 18DirectX 11 versus OpenGL 4.0
OpenGL has long been considered a rival graphics API to Direct3D OpenGL
supports platforms outside of Windows-based operating systems, such as Mac
implementation at least), and a variety of mobile devices such as cell phones
and PDAs, along with other platforms Although the native device creation of
OpenGL can differ from one platform to another, the rest of the API is
considered platform independent, not including the long history of
hardware-specific extensions and features from competing entities within the OpenGL
camp DirectX, on the other hand, is available on the various Windows OSs and
the Xbox game consoles To be considered DirectX 10 or 11 compatible,
hardware must adhere to a strict compatibility list, whereas prior to DirectX
10 this was not always the case In the case of OpenGL this often led to
vendor-specific extensions that worked on limited hardware Incompatibilities within
the hardware market caused rework when trying to achieve the same result on
all supported devices
The whole Direct3D versus OpenGL debate can often seem like a religious one,
but the fact is that for many years OpenGL has lagged behind Direct3D
Microsoft has done a great job evolving Direct3D and improving it throughout
the years, but OpenGL has only lagged behind, not keeping its promises as each
new version is released, and time and time again has suffered from the same
problems of yesteryear When OpenGL 3.0 was first announced, it was thought
that OpenGL would finally move back into a position to rival Direct3D
Unfortunately, the world of OpenGL has gone through its share of ups and
downs, both within the group behind it and with how the API stacked against
Direct3D, and Direct3D has continued to dominate
OpenGL 4.0 catches up to many of the publicized features of DirectX 11, most
notably through the support of general-purpose computing using OpenCL and
tessellation, and is positioning itself to be a step closer to the promises that were
never delivered in the past, most notably with OpenGL 2.0 and OpenGL 3.0
Although OpenGL is not out of the race yet, it unfortunately needs a lot of work
to not only truly rival DirectX but also to win back the hearts and minds of
numerous Even if the API catches up, the graphics API race is a lot like high
school where the popular kid wins the election
What Is DirectX? 5
Trang 19Why Is DirectX Needed?
Before the release of the Windows operating system, developers were writinggames for DOS This single-threaded, non-GUI operating system provideddevelopers with a direct path between their application code and the hardware
it was running on This had both its advantages and problems For instance,because there was a direct path between the game code and the hardware,developers could pull every ounce of power out of the machine, giving themcomplete control over how their game performed The downside included theneed to either write directly to the hardware or use a variety of third-partylibraries for any hardware they wanted their game title to support, includingeven common hardware such as video and sound cards
Video cards were especially confusing because not all video cards followed thesame standard Even though most video cards supported a series of commonresolutions, developers were forced to access video memory directly This madeeven drawing to the screen difficult Developers were definitely looking for abetter and easier way
When Windows 3.1 was released, it carried with it the same limitations thatDOS had Since Windows ran on top of DOS, it severely limited the resourcesavailable to games and took away the direct access developers had enjoyed for solong Most games written to support Windows at the time consisted mainly ofcard and board games, while most games continued to support DOS only.Microsoft released DX1 as a way of enticing developers to make games for
DOS-based systems
Microsoft’s release of Windows 95 didn’t eliminate any of these problems untilthe release of DirectX 1, also known as the Windows Games SDK It gavedevelopers a single library to write to, placing a common layer between theirgame and the PC hardware; drawing graphics to the screen had just become awhole lot easier The first version of DirectX still didn’t provide support for allthe hardware out there, but it was a great starting point in giving gamedevelopers what they had been waiting for Over the years, there have beenmultiple releases of DirectX, each one improving and adding support for newtechnologies such as network play, streaming audio, and new kinds of input
Trang 20devices The latest version of DirectX includes Direct3D 11, which is compatible
with Microsoft Windows Vista and Windows 7 operating systems
How DirectX Is Put Together
DirectX is based on a collection of code libraries, each providing a common set
of functionality needed for games and multimedia applications To make sure
that your game only has to link to the necessary functionality, DirectX is
separated into multiple components
The Components of DirectX 11
The DirectX API is split into multiple components, each representing a different
aspect of the system Each API can be used independently of one another,
thereby allowing the addition of only the functionality your game requires In
the latest version of DirectX, some of the components were updated, such as
Direct3D, while others are now being maintained at their previous levels by
Microsoft until their removal (if they are deprecated) The components within
DirectX can be upgraded individually as new functionality is required
Direct2D
Direct2D is used for 2D graphics within Win32 applications It is capable of
rendering high-performance vector graphics
DirectWrite
DirectWrite is used for fonts and text rendering within a Direct2D application
DXGI
The DirectX Graphics Infrastructure, also known as DXGI, is used for the
creation of Direct3D swap chains and the enumeration of device adapters
Direct3D
Direct3D is used for all 3D graphics in DirectX It is also the API that receives
the most attention and updates Throughout this book we will largely focus on
Direct3D
How DirectX Is Put Together 7
Trang 21XAudio2 is a lower-level audio processing API that is part of the XDK (XboxDevelopment Kit) and, now, the DirectX SDK XAudio2 is the replacement forDirectSound The original XAudio was used on the first Xbox video game console
XACT3
XACT3 is a higher-level audio processing API built on top of XAudio2 XACT3allows developers to use the Cross-Platform Audio Creation Tool to authorsounds in their applications Developers would use XAudio2 if they needed low-level control of their audio system or if they wanted to build their own higher-level audio system similar to XACT3 XACT3, as discussed in Appendix B,
“Audio in DirectX” from the companion website, is a powerful and incredibleeasy tool to use for game audio
XInput
XInput is the input API for the XDK and the DirectX SDK and is used forprocessing of input from all Xbox 360 controllers Essentially any controller youcan use with your Xbox 360 can be used with the PC, and XInput is the API youuse for working with these devices These devices include not only Xboxgamepad controllers but also Rock Band and Guitar Hero instrument controllers(e.g., guitars, drums, and so forth), Big Button controllers (shipped with thegame Scene It), arcade sticks (e.g., the Tekken 6 arcade stick), and so much more.XInput is the replacement for DirectInput
Trang 22N o t e
XNA Game Studio is a game development tool built on top of DirectX that allows developers to
create games for both the Xbox 360 and Windows PCs using C# and NET XNA Math is the name
of the math library in the new DirectX SDK and can be used outside of the XNA Game Studio You
do not need to download the XNA Game Studio SDK.
DirectCompute
DirectCompute is a new API added to DirectX 11 that allows for
general-purpose multi threading computing using the GPU The GPU has the ability to
process many tasks in parallel, such as physics, video compression and
decom-pression, audio processing, and much more Not all tasks are suited for the GPU,
but for those that are, the possibilities are tremendous
For more information on DirectCompute, check out the book Game
Develop-ment with Microsoft’s DirectCompute for Beginners
DirectSetup
Once your game is complete, you’ll want to show it to others DirectSetup gives
you the functionality to install the latest version of DirectX on the user’s
computer It also has the ability to check the latest installed version of DirectX
Windows Games Explorer
The Games Explorer is a feature of Windows Vista and Windows 7 that allows
developers to present their games on those OSs The Games Explorer handles
things such as the game’s display, title, rating, description, region-specific box
art, content ratings (e.g., M for Mature, T for Teens, etc.), game statistics and
notifications, parental controls, and more The DirectX SDK provides plenty of
information on how to use the Games Explorer for your own games and could
be very useful when it comes time to ship a game An example of the Games
Explorer can be seen in Figure 1.1
DirectInput
DirectInput is an API for detecting input with keyboards, mice, and joysticks
Today XInput is used for all game controllers For keyboards and mice we can
use Win32 functions or we can use DirectInput, which we’ll examine later in the
book in Chapter 5 According to the DirectX SDK, DirectInput will remain in its
current form until new technologies replace it
How DirectX Is Put Together 9
Trang 23Obsolete DirectX Components
The following components are either deprecated or removed from the DirectXSDK:
DirectDraw
Once used for 2D rendering, today we can use either Direct2D or Direct3D for2D graphics DirectDraw was merged with Direct3D into what was calledDirectX Graphics in DirectX 8
Figure 1.1
An example of the Games Explorer in Windows 7.
Trang 24N o t e
In previous versions of DirectX, 2D drawing functionality was provided by a component called
DirectDraw Because DirectDraw is no longer being updated, you should perform all drawing using
Direct3D or Direct2D.
DirectPlay
DirectPlay was used for networking capabilities for online games It was built on
top of the UDP protocol (User Datagram Protocol) and served as a higher-level
abstraction for network communication Today the API has been removed and
is no longer part of the DirectX SDK DirectPlay was deprecated in favor of
Games for Windows Live on the PC and Xbox Live on Xbox consoles
DirectShow
DirectShow was used for multimedia rendering and recording This meant
DirectShow was able to display video files in multiple common formats, provide
DVD navigation, and much more Today DirectShow is part of the Windows
SDK and is no longer part of the DirectX SDK Alternatively, Windows Vista
and Windows 7 users can use Microsoft’s Media Foundations for media content,
which is also part of the Windows SDK This is useful for video games if they
need to display CG cut-scenes and video files
DirectMusic
DirectMusic is now a deprecated API from the DirectX 7 and earlier days for
playing audio content in applications DirectMusic offers low-level access to
audio and hardware and has been a topic in DirectX books and tutorials for
many years Today we use XAudio2 (low-level) or XACT3 (high-level) for audio
in games and media applications
DirectSound
DirectSound is another deprecated audio API used to give low-level access to
developers for their audio needs XAudio2 is its replacement We discuss audio
in detail in Appendix B,“Audio in DirectX,” located on the companion website
The Components Object Model
The DirectX API is based on the Component Object Model (COM) COM
objects consist of a collection of interfaces that expose methods that developers
How DirectX Is Put Together 11
Trang 25use to access DirectX COM objects are normal DLL files that have beenregistered with the system to provide support for specific hardware in themachine For DirectX COM objects, registration happens during the installation
of DirectX While similar to Cþþ objects, COM objects require the use of aninterface to access the methods within them This is actually an advantage overstandard objects because multiple versions of an interface can be present within
a COM object, allowing for backward compatibility
For instance, each version of DirectX included a new DirectDraw interfaceaccessible through the API, while still containing the previous version so as not
to break existing code Therefore, games created using DirectX 7 are able towork with DirectX 9 In other words, older games can be installed and playedusing the latest version of the DirectX runtime
An additional advantage to COM objects is their ability to work with multiplelanguages, not just Cþþ Developers can use Visual Basic, Cþþ, or C# and stilluse the same DirectX libraries As Microsoft updates and adds new functionality
to DirectX, the version numbers of each updated component will increase You’llfind that not all the included components exist at the same version level Forinstance, DirectInput remains at version 8.0, while Direct3D is now at version 11
Introducing Direct3D 11
The release of Windows 7 has brought with it the release of Direct3D 11.Direct3D 11 is compatible with Windows Vista and Windows 7, along withDirectX 10-class hardware Certain features of DirectX 11, such as tessellationand Shader Model 5.0, require DirectX 11-class hardware But most of the APIcan be used with DirectX 10-class hardware
Stages of Direct3D 11
Direct3D is more than just an API; it’s a tool for transforming geometric shapesand images into a living, breathing world Even though you can treat manypieces of Direct3D as a black box and not have to worry about the implemen-tation details, it is a good idea to understand at least an overview of how itworks
Direct3D processes your scene in multiple stages, with each stage performing aspecific set of tasks resulting in a final image These stages are known as Direct3D’srendering pipeline, and a screenshot of each can be seen in Figure 1.2
Trang 26The first stage of Direct3D’s pipeline, called the Input-Assembler (IA) stage, can
be thought of as the building-block stage In this stage we set the geometry we
are going to render along with the necessary information Direct3D needs to
perform that task
The second stage is the vertex shader (VS) stage A vertex is a single point that
makes up a shape, such as a triangle In a vertex shader we can run code that
operates on each vertex, much of which depends on the effect we are setting up
for Shaders will be discussed more throughout this entire book A vertex shader
always takes a single vertex as input and outputs a single vertex This vertex data
was supplied by the data set using the input assembler
The third, fourth, and fifth stages are optional stages that deal with tessellation
Tessellation is an advanced topic that uses two new shaders to Direct3D called
the hull and domain shaders Hardware tessellation, in a nutshell, is the process
of taking input geometry and increasing or decreasing its level of detail This
allows for very high polygonal models to be rendered in real time with polygon
counts in the hundreds of thousands or even the millions By having the
hardware create the detail of the geometry, the application only has to submit a
Figure 1.2
The stages of Direct3D 11.
Introducing Direct3D 11 13
Trang 27small amount of data that defines the low-level model This model can be in theform of patches, which is a 3D modeling The hardware takes this low-levelmodel and makes it higher level Subdividing polygons means to take a polygonand divide it into smaller pieces.
The hull shader takes its input from the output of the vertex shader, which isoperating on control points and data versus traditional vertices, and producesoutput control points for what are known as patches The tessellation stage,which appears between the hull shader and domain shader stages, is a fixed-function stage that takes the output from the hull shader and subdivides the data
on hardware The domain shader is responsible for generating the vertex of asubdivided point
The sixth stage, the geometry shader (GS), is also an optional shader stage If there is
no tessellation being performed, the geometry shader stage occurs after the vertexshader stage Geometry shaders operate on entire shapes such as triangles, whereasthe vertex shader operates on a single point of a shape The geometry shader has theability to essentially create or destroy geometry as needed, which depends largely onthe effect you are trying to create One common example of geometry shaders isgenerating shadowing geometry from a model by creating what is known as ashadow volume Another example is the generation of particles used to create particleeffects such as rain or explosions by taking a list of points that act as the center of theparticles and generating polygons around them
The seventh stage, the Rasterizer, has the job of determining what pixels are visiblethrough clipping and culling geometry (we’ll discuss this in Chapter 6), setting upthe pixel shaders, and determining how the pixel shaders will be invoked
The eighth stage is the pixel shader (PS) stage In the pixel shader stage, theshader receives the geometric data from all previous stages and is used to shadethe pixels (sometimes referred to as fragments) that comprise that shape Theoutput of the pixel shader is a single color value that will be used by the finalstage to build the final image displayed to the screen If there are no tessellation
or geometry shaders, the pixel shader receives its input from the vertex shaderdirectly The input to the pixel shader is technically interpolated data—that is,data that is generated between the points (vertices) of a shape We’ll discuss thismore in the next chapter
Trang 28The final stage, the output merger (OM) stage, is where it all comes together.
The OM takes all of the output pieces from the other stages of the pipeline and
builds up the final image to send to the screen
Direct3D 11 Considerations
Some of you may already be familiar with writing games using DirectX, and if
so, there are a few things you need to be aware of when converting your game to
the latest version of Direct3D If updating from Direct3D 10 to Direct3D 11, the
process is fairly straightforward, and most of the work will be to replace
Direct3D 10 calls with their Direct3D 11 equivalent Direct3D 11 is more of a
superset of Direct3D 10 and 10.1, so there is not a lot that will need to be done
Going from Direct3D 9.0 to 11.0 is another story
When coming to Direct3D 11 from Direct3D 9, the biggest change is the
removal of the fixed-function pipeline Previously you could choose one of the
default ways to process your 3D scene, and Direct3D would handle the clipping,
lighting, and the shading Today, with D3D10 and D3D11, all this functionality
needs to be specifically handled using the programmable pipeline Chapter 7 is
about shaders, and its purpose is to bring you fully up to speed with all that is
included in Direct3D 11 Throughout the entire book we’ll be using shaders and
discussing them as necessary before we reach the comprehensive discussion in
Chapter 7
Another of the more major changes is the removal of the CAPS bits In previous
versions of Direct3D, you had to check the capabilities of the underlying video
hardware to make sure that certain functionality like pixel shaders was available
to use Now, any features not provided by the hardware are emulated by the
system in software, ensuring you always have the full range of functionality to
play with This will greatly simplify the initialization code for games using
D3D10 It is also much needed, since in the past some hardware vendors
supported only a subset of features, which caused issues when dealing with
supporting different pieces of hardware To be considered DirectX 10- or
11-compatible today, hardware must strictly follow guidelines for compliance
Direct3D 9.0 is close to having a completely different API It is not possible to do
massive copy and paste on function names like you could get away with
changing code from Direct3D 10.0 to 11.0 In this situation you’ll most likely
Direct3D 11 Considerations 15
Trang 29be better off creating a new rendering layer for your game and working off thestrengths of Direct3D 11 instead of trying to do a line-by-line search andreplace.
DirectX Tools
The DirectX SDK contains a wealth of information and tools for many related topics The SDK itself should be explored by all developers using DirectXbecause there are tremendously well documented and well developed tools thataid in the learning and/or developing of DirectX applications In this section wewill briefly take a look at some of the tools available in the DirectX SDK
DirectX-Sample Browser and Documentation
The DirectX SDK Sample Browser is a tool that displays all of the exampledemos, technical papers, tutorials, articles, and tools that come with the DirectXSDK The Sample Browser lists dozens of entries that include DirectX 11,DirectX 10, and DirectX 9 Whenever a new version of the SDK is released, it isrecommended that you check out the Sample Browser You might find theimplementation to a new technology or effect, a useful tutorial, or technicalinformation about everything DirectX
A screenshot of the Sample Browser can be seen in Figure 1.3 The samplebrowser can be found on the Start menu inside the subfolder for your DirectXSDK installation
Also of valuable use are the DirectX documentation and the Graphics umentation The graphics area of the SDK has its own documentation, which isimportant to know if you are looking for something graphics related and happen
doc-to open the wrong documentation file Also, Microsoft’s MSDN website has all
of this documentation and more available online
PIX
PIX is a tool used for the debugging and analysis of Direct3D applications asthey are executing PIX can give valuable information such as API calls, timingstatistics, and mesh information before and after transformation, to name a few.PIX can also be used for the debugging of shader code on the GPU, along withbreakpoints and the ability to step through code
Trang 30Caps Viewer
The DirectX Caps Viewer shows information about the hardware’s capabilities
by way of detailing its support for Direct3D, DirectDraw, DirectSound, and
DirectInput Every piece of information about what the hardware supports and
its version are displayed by this tool A screenshot of the Caps Viewer can be
seen in Figure 1.4
Diagnostic Tools
The DirectX Diagnostic tool is used to test various components of DirectX to see
if they are working properly The diagnostic tool is used to create diagnostic
Figure 1.3
The DirectX SDK Sample Browser.
DirectX Tools 17
Trang 31reports that can be saved to a file and/or sent to Microsoft Sending the report toMicrosoft is done via the Report button on the More Help tab of the tool If yoususpect some components are not working properly on a specific machine,running this tool can provide some insight.
Trang 32texture formats supported by DirectX 9, not DirectX 10 or 11 If you are looking
to create images compressed with DXT1 through DXT5, this tool can do the job
N o t e
BC6 and BC7 are the new formats not supported by this tool The “BC” has replaced the “DXT” in
these compression formats.
The DirectX SDK also includes the Texture Converter The Texture Converter is
included with the TXVIEW.dll, which is installed as part of the DirectX SDK
installation The purpose of the Texture Converter is to convert an image from
one format to another The file formats that can be seen include:
The Texture Converter works by right-clicking on an image (or multiple images)
in the Windows Explorer and selecting Convert to File Format from the
drop-down list Once the dialog box appears, set the properties of the image you are
converting by setting its output size, format, and output filename, to name a few
You could also use the texture conversion command-line tool called TexConv
exe or TexConvEx.exe for Direct3D 10 and 11 textures The Texture Converter
extension was last compatible with DirectX 9
Error Lookup
The DirectX Error Lookup tool displays a description of any error code received
while running your DirectX applications You can enter the error code into this
application, hit the Lookup button, and it will describe the error to you Not all
DirectX Tools 19
Trang 33errors are clear, and this tool can be useful The Error Lookup tool can be found
in the Utilities folder of your DirectX SDK installation
Control Panel
The DirectX Control Panel, located in the Utilities folder of the DirectX SDK, isused to examine and modify the properties of various DirectX components.With the Control Panel tool you can do the following:
n Enable the debug layer of Direct3D 10/11
n Change the debug output level and settings for use during development
n View driver information
n View version information for the various components
Cross-Platform Audio Creation Tool
The Cross-Platform Audio Creation tool is a GUI tool (also available with theDirectX SDK is a command-line alternative) for creating audio files used byXACT3, which is DirectX’s high-level audio API/component This tool is what
we’ll use to take our audio clip files and organize them into various banks, aprocess that is discussed in more detail in Appendix B (online)
A screenshot of the Cross-Platform Audio Creation tool can be seen in Figure 1.5.The XACT3 tool can be used to create audio files for Windows PC and the Xbox
360 For those doing game development using XNA, you can deploy a version ofthe audio files that matches the byte-ordering format of the processor within the
360 Since the Xbox 360 uses an architecture based on PowerPC, the same outputfiles for the PC cannot be used interchangeably with the Xbox 360 This will notaffect us in this book since this book assumes game development on an x86processor using DirectX 11 on Windows Vista or a Windows 7 PC
Game Definition File Editor
The Game Definition File Editor is used to create localized game definition filesfor Windows Vista and Windows 7 The information for a game definition file isdisplayed on the Games Explorer, which was discussed during the section titled
Trang 34“The Components of DirectX 11.” A screenshot of the editor can be seen in
Figure 1.6
The Game Definition File Editor allows you to create properties for the game’s
release date, its Games Explorer icon and box art, its rating (e.g., Teen, Mature,
etc.), its name and description, and a host of other properties There is a detailed
tutorial of using the Game Definition File Editor that comes with the DirectX
SDK documentation You can also find this tutorial on the MSDN website by
searching for“Game Definition File Editor: Tool Tutorial.”
Down-Level Hardware
DirectX 11 supports a concept known as down-level hardware When DirectX
10 and Windows Vista were released, they were built for a new driver model and
hardware Although DirectX 11 is its own version, it has the ability to target the
Figure 1.5
The Cross-Platform Audio Creation tool.
DirectX Tools 21
Trang 35DirectX 10.0 and 10.1 class of hardware with a single set of functions We’ll seethis in Chapter 2 when we build the first demos to check for compatibility withDirectX 11 first, and then for DirectX 10.1 and 10.0 if support for 11 isn’t there.Even if the application does choose DirectX 10.1 or 10.0, the same API callsapply, and as long as we are using Shader Model 4.0 and features not required byDirectX 11, the application will work just fine on that hardware If you do nothave DirectX 11.0 hardware it’s OK, since DirectX 10.0 hardware will work forall samples in this book.
Figure 1.6
The Game Definition File Editor.
Trang 36As you go through the process of learning DirectX, don’t worry if things seem
overwhelming at times If this is your first time with video game graphics
programming, then DirectX, or OpenGL for that matter, will naturally have a
steep learning curve If you have experience with DirectX, you’ll find things are
much easier and much cleaner with Direct3D 10/11 If you are coming from
OpenGL, you’ll already have a handle on the more difficult and involved general
graphics programming concepts, and you can focus on learning the specifics of
the API itself
When learning DirectX, it is useful to pick a system and write as many samples
with it as you can The goal is to start small and work your way up By starting
small you allow yourself a realistic goal that you can build upon until you reach
your goal of DirectX mastery As you code demo by demo, before you know it
things start to make sense and fall into place If you ever get stuck, remember
you’re not alone; sites like UltimateGameProgramming.com, GameDev.net, and
Microsoft’s MSDN are great places to find help Like many things in life, the best
way to learn is to do it again and again until you’ve mastered the craft
Chapter Questions
Answers to all chapter review questions can be found in Appendix A on this
book’s companion website
2 Which is not a feature of DirectX 11?
A Fixed-function rendering pipeline
B Multithreaded GPU
C Offers HDR texture compression
D None of the above
3 Which version of DirectX does the Xbox 360 use?
A A modified version of DirectX 10
B A modified version of DirectX 11
Chapter Questions 23
Trang 37C A modified version of DirectX 9
D A modified version of DirectX 8
4 DirectCompute was introduced in which version of DirectX?
A DirectX 11
B DirectX 10
C DirectX 9
D DirectX on the Xbox 360
5 DirectX 11 introduces which shader model?
A Shader Model 4.0
B Shader Model 4.1
C Shader Model 5.0
D None of the above
6 Which stage appears after the pixel shader?
A The geometry shader
B Output merger
C Hull and domain shaders (for tessellation)
D Vertex shader
7 The DirectX Control Panel is?
A There is no Control Panel in the DirectX SDK
B Used to install/uninstall DirectX
C An extension to the Windows 7 Control Panel
D Used to examine component properties
8 The Game Definition File is used for what purpose?
A To edit the game’s resources, such as images and models
B To create a game’s help manual
C To create a game installer
D For creating localization files for the Games Explorer
9 PIX is what type of tool within the DirectX SDK?
A Used for performance analysis
B Used for texture viewing
C Used for texture converting
D None of the above
10 How many stages did we discuss for Direct3D 11?
A 12
B 7
C 9
D 11
Trang 3811 Geometry shaders are used for tessellation (true or false).
A True
B False
12 The geometry shader stage occurs before the vertex stage and after the
pixel stage (true or false)
15 Compute shaders is a new shader type in DirectX 11 for general-purpose
computing (true or false)
A True
B False
Chapter Questions 25
Trang 40Your First DirectX
Program
The best way to begin learning DirectX is to start at the beginning by creatingsimple demo applications In this chapter we’ll take you step-by-step through theprocess of creating your very first DirectX application, specifically focusing onDirect3D By the end of this chapter you will have a firm understanding of thesetup of Direct3D from start to finish
In this chapter:
n How to create a project
n How to initialize DirectX
n How to clear the screen
n How to display a scene
Creating the Project
This book assumes you’ve already had experience creating C++ projects andworking within Visual Studio In this section and the one to follow we’ll brieflycover the initial setup of a Win32 application We’ll modify this code throughoutthe chapter to include Direct3D initialization and basic rendering By the end ofthe chapter we’ll have a set of code used to create and initialize Direct3D that wecan use for all demos throughout this book
Chapter 2
27