DirectX 3D Graphics Programming Bible Preface | Part I: The Fundamentals Chapter 1: The PC as a Graphics Machine Chapter 2: Graphics Representation and Modeling Chapter 3: 3D Image Transformations Chapter 4: 3D Rendering Chapter 5: Computer Animation Chapter 6: Windows API Programming | Part II: DirectDraw Chapter 7: DirectDraw Fundamentals Chapter 8: DirectDraw Configuration and Setup Chapter 9: Direct Access to Video Memory Chapter 10: Blitting and Blit-time Transformations Chapter 11: Rendering Bitmaps in DirectDraw Chapter 12: Animation Techniques Chapter 13: Animation Programming | Part III: 3D Graphics with Direct3D Chapter 14: Introducing Direct3D Chapter 15: Fundamentals of Retained Mode Programming Chapter 16: System-Level Operations Chapter 17: Device-Level Operations Chapter 18: Viewport-Level Operations | Part IV: Direct3D Programming Chapter 19: Local Frame Operations Chapter 20: Frame Attributes and Scene-Level Controls Chapter 21: Mesh-Level Operations Chapter 22: Textures and Materials Chapter 23: Decals and Mipmaps Chapter 24: Lights and Shadows Chapter 25: 3D Animation | Part V: Appendices Appendix A: Windows and DirectX Structures Appendix B: Ternary Raster Operation Codes Appendix C: DirectX Templates Bibliography Color Plates DirectX 3D Graphics Programming Bible Julio Sanchez Maria P Canton Published by IDG Books Worldwide, Inc An International Data Group Company 919 E Hillsdale Blvd., Suite 400 Foster City, CA 94404 www.idgbooks.com (IDG Books Worldwide Web site) Copyright © 2000 IDG Books Worldwide, Inc All rights reserved No part of this book, including interior design, cover design, and icons, may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without the prior written permission of the publisher Distributed in the United States by IDG Books Worldwide, Inc Distributed by CDG Books Canada Inc for Canada; by Transworld Publishers Limited in the United Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for Sweden; by IDG Books Australia Publishing Corporation Pty Ltd for Australia and New Zealand; by TransQuest Publishers Pte Ltd for Singapore, Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc for Taiwan; by ICG Muse, Inc for Japan; by Intersoft for South Africa; by Eyrolles for France; by International Thomson Publishing for Germany, Austria, and Switzerland; by Distribuidora Cuspide for Argentina; by LR International for Brazil; by Galileo Libros for Chile; by Ediciones ZETA S.C.R Ltda for Peru; by WS Computer Publishing Corporation, Inc., for the Philippines; by Contemporanea de Ediciones for Venezuela; by Express Computer Distributors for the Caribbean and West Indies; by Micronesia Media Distributor, Inc for Micronesia; by Chips Computadoras S.A de C.V for Mexico; by Editorial Norma de Panama S.A for Panama; by American Bookshops for Finland For general information on IDG Books Worldwide's books in the U.S., please call our Consumer Customer Service department at 800-762-2974 For reseller information, including discounts and premium sales, please call our Reseller Customer Service department at 800-434-3422 For information on where to purchase IDG Books Worldwide's books outside the U.S., please contact our International Sales department at 317-596-5530 or fax 317-572-4002 For consumer information on foreign language translations, please contact our Customer Service department at 800-434-3422, fax 317-572-4002, or e-mail rights@idgbooks.com For information on licensing foreign or domestic rights, please phone +1-650-653-7098 For sales inquiries and special prices for bulk quantities, please contact our Order Services department at 800-434-3422 or write to the address above For information on using IDG Books Worldwide's books in the classroom or for ordering examination copies, please contact our Educational Sales department at 800-434-2086 or fax 317572-4005 For press review copies, author interviews, or other publicity information, please contact our Public Relations department at 650-653-7000 or fax 650-653-7500 For authorization to photocopy items for corporate, personal, or educational use, please contact Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, or fax 978-750-4470 LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK THE PUBLISHER AND AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS PARAGRAPH NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES Trademarks: All brand names and product names used in this book are trade names, service marks, trademarks, or registered trademarks of their respective owners IDG Books Worldwide is not associated with any product or vendor mentioned in this book Credits Acquisitions Editors Greg Croy John Osborn Project Editor Matthew E Lusher Technical Editor Susan Schilling Copy Editor Mildred Sanchez Media Development Specialist Jason Luster Permissions Editor Lenora Chin Sell Media Development Manager Stephen Noetzel Project Coordinators Linda Marousek Danette Nurse Joe Shines Graphics and Production Specialists Robert Bilhmayer Jude Levinson Michael Lewis Victor Pérez-Varela Dina F Quan Book Designer Drew R Moore Illustrators Brian Drumm Mary Jo Richards Proofreading and Indexing York Production Services Cover Illustration Contributor David B Mattingly Cover Illustration Peter Kowaleszyn, MBD Design, SF About the Authors Julio Sanchez is an associate professor of Computer Science at Minnesota State University, Mankato Julio is the author of 17 books in the field of computer programming, five of which have been translated into foreign languages He also teaches courses and seminars in C++, Windows, and Java programming at Minnesota State University Maria P Canton is the president of Skipanon Software, a programming and consulting company that has been in business since 1983 She is also a faculty member at Minnesota State University, Mankato Maria is the principal author of one book and the coauthor of 13 other titles in the field of computer programming Preface This book covers 3D graphics programming in Windows, using DirectX, and coding in C++ It assumes that you have a basic understanding of C++ Although many applications could profit from object-oriented constructs, we not use them in this book in order to avoid the additional complications The book includes one chapter (Chapter 6) on the fundamentals of Windows API programming, but it alone may be insufficient for someone who is totally unfamiliar with this topic Readers with no previous Windows programming experience may need to devote some time to acquiring these skills before plunging into the details of 3D graphics We recommend our own book titled Windows Graphics Programming, published by M & T Books This title was designed to provide the necessary skills in Windows graphics without overwhelming the reader with too many complications and details Nevertheless, any good book on Windows API programming would serve this purpose, such as the ones by Petzold, Rector and Newcomer, and Schildt Their titles can be found in the Bibliography This book is for you if you wish to learn Windows 3D graphics and to apply it to the development of computer games, simulations, or any form of 3D, high-performance, multimedia programming The road is not an easy one; there is much to learn 3D is rightly called the "rocket science" of programming However, the rewards of working on the cutting edge of this technology are enormous What Is in the Book In this book we approach Windows programming at its most basic level, that is, using the Windows Application Programming Interface (API) We not use the Microsoft Foundation Class Library (MFC) or other wrapper functions that are furnished as part of commercial development environments Microsoft's MFC is an object-oriented framework that encapsulates many of the functions in the API It is intended for use with Developer's Studio App Wizard, which facilitates creating a program skeleton for a Windows application But the MFC interface introduces a processing overhead that slows down execution and limits program functionality Graphics programs in general, and 3D applications in particular, cannot afford this overhead Furthermore, DirectX provides no special support for MFC; therefore, its use offers no advantages to the graphics programmer Please note that although we not use the wrapper functions of the MFC, we rely heavily on the other tools that are part of the Visual C++ development package These include resource editors for creating menus, dialog boxes, icons, bitmaps, and other standard program components There are no advantages to hand-coding these program elements Part I of this book is devoted to the fundamentals of 3D graphics Here we present the tools and resources of PC graphics programming and introduce the reader to various graphics representations, image modeling techniques, mathematical transformations, data rendering operations, and animation The material for this part was selected based on the minimal knowledge required for understanding and using DirectX 3D graphics The theoretical topics and the mathematics have been reduced to the bare essentials By presenting this material first, we avoid the distraction of having to explain theoretical concepts when discussing programming topics This first part also contains a chapter on the fundamentals of Windows API programming Part II covers DirectDraw DirectDraw is the 2D graphics environment in DirectX We devote considerable space to DirectDraw programming for two reasons The first one is that 3D graphics in DirectX are based on DirectDraw; a 3D application executes in the DirectDraw environment The second reason is that few commercial applications are exclusively 3D Most programs use 3D functions to model some of the objects, whereas others, such as backgrounds and sprites, are rendered in 2D graphics Mastering 2D in DirectDraw is an essential skill for the DirectX 3D programmer Parts III and IV are devoted to 3D graphics programming in DirectX retained mode Part III introduces 3D graphics and discusses retained mode programming at the system, device, and viewport levels Part IV discusses programming techniques at the lower levels of the retained mode interface We not discuss immediate mode programming, but not because we consider it unimportant Our reason for not including immediate mode was a simple matter of space To present a bare-bones discussion of DirectX immediate mode would have required substantially reducing and diluting the rest of the material The result would have been a book that visited many topics superficially, but no one subject in depth Because we believe that retained mode is the most reasonable development environment at the application level, as well as the easiest way to learn 3D graphics programming, we concentrated on it Other factors that influenced our choice are mentioned in the following section Direct3D: Past and Future In more than one sense 3D graphics programming is not for the faint-hearted We believe that at present, any Windows 3D programming tool, facility, or development environment, should have a warning label stating that it is work in progress If, as a programmer, you need to operate in a stable, well-defined, consistently evolving platform, then 3D graphics should not be your chosen field Although 2D graphics in DirectX always take place in DirectDraw, the 3D DirectX interface changes so much and so frequently that, for many programmers, it is a challenge just to keep up with the updates When we began writing this book Microsoft's DirectX was recently released We finished it under DirectX Each of these DirectX versions (5, 6, and 7) contained major expansions, additions, and corrections to the previous ones Furthermore, each consecutive version of the DirectX SDK seemed to reflect a new vision of the 3D graphics paradigm At this time the future of 3D graphics in DirectX remains undefined For DirectX 8, originally planned for release in the first half of the year 2000, Microsoft announced a completely new development environment, which was code-named Fahrenheit The Fahrenheit product was being developed as a joint venture with Silicon Graphics Corporation Silicon Graphics is the creator of OpenGL, a 3D environment that has gained considerable prevalence in graphics workstations Early this year, Silicon Graphics pulled out of the Fahrenheit project Microsoft has not yet said if it will continue to develop Fahrenheit on its own, or if the project will be scrapped What will be in DirectX is now a mystery All of this generated considerable uncertainty regarding the future of the retained mode and immediate mode interfaces of DirectX Will Fahrenheit replace retained mode, immediate mode, neither, or both? Because we are not even sure that there will be a Fahrenheit product, or what else DirectX may contain, any answer is pure guesswork This state-of-affairs in 3D development environments and tools will continue to affect DirectX for many years to come The fact that Windows is a Microsoft product further complicates matters Currently DirectX contains three 3D development environments: retained mode, immediate mode, and the DirectX foundation In the near future the product now called Fahrenheit may be added to the list Not long after the release of a 3D toolkit or environment, programmers start creating software based on the new interface These new products are marketed with the expectation that they will continue to execute in future versions of the operating system As a consequence Microsoft is compelled to provide support for all interfaces or development environments, even after they become outdated, or even obsolete This all means that a new 3D graphics paradigm does not replace the existing ones because the old interfaces have to be kept operational so as not to break commercial code In the near future a DirectX 3D programmer may be able to work under retained mode, immediate mode, DirectX foundation, or Fahrenheit—all of this not mentioning other 3D development tools that exist outside of DirectX, such as OpenGL or the proprietary APIs of the various chip manufacturers Out of this quagmire of options and development tools we selected DirectX retained mode Some may question the validity of this choice In DirectX 7, Microsoft announced that retained mode is now in a maintenance phase This statement is interpreted to mean that Microsoft lost interest in the future development in retained mode Another fact is that many professional DirectX 3D programmers work in immediate mode, and recommend it as a more powerful alternative Although this is true, it is also undeniable that immediate mode complicates 3D programming by several orders of magnitude Furthermore, there is no assurance that the next release of DirectX will not place immediate mode in a maintenance phase Retained mode, on the other hand, is easier to learn and use The fact that it is not being constantly tinkered with at this stage could be seen as an asset, rather than a drawback We have no doubts that Windows and DirectX must continue to Template: Frame UUID Member Name Optional Data Objects None (see list) Description Defines a frame Currently, the frame can contain objects of the type Mesh and a FrameTransformMatrix Optional Data Objects The following optional data elements are used by Direct3D retained mode FrameTransformMatrix If this element is not present, no local transform is applied to the frame Mesh Any number of mesh objects that become children of the frame These objects can be specified inline or by reference Template: FloatKeys UUID Member Name Type nValues DWORD values array FLOAT nValues Description Defines an array of floating-point numbers and the number of floats in that array This is used for defining sets of animation keys Template: TimedFloatKeys UUID Member Name Type time DWORD tfkeys FloatKeys Description Defines a set of floats and a positive time used in animations Template: AnimationKey UUID Member Name Type Optional Array Size keyType DWORD nKeys DWORD keys array nKeys TimedFloatKeys Description Defines a set of animation keys The keyType member uses the integers 0, 1, and to specify whether the keys are rotation, scale, or position keys, respectively Template: AnimationOptions UUID Member Name Type openclosed DWORD positionquality DWORD Description Enables setting the Direct3D retained mode animation options The openclosed member can be either for a closed or for an open animation The positionquality member is used to set the position quality for any position keys specified and can either be for spline positions or for linear positions By default, an animation is closed Template: Animation UUID Member Name Optional Data Objects None (see list) Description Contains animations referencing a previous frame It should contain one reference to a frame and at least one set of AnimationKeys It also can contain an AnimationOptions data object Optional Data Objects The following optional data elements are used by Direct3D retained mode AnimationKey An animation is meaningless without AnimationKeys AnimationOptions If this element is not present, an animation is closed Template: AnimationSet UUID Member Name Optional Data Objects none Animation Description Contains one or more Animation objects and is the equivalent to the Direct3D retained mode concept of animation sets This means each animation within an animation set has the same time at any given point Increasing the animation set's time will increase the time for all the animations it contains Bibliography Bargen, Bradley and Peter Donnelly Inside DirectX Microsoft Press, 1998 Box, Don Essential COM Addison-Wesley, 1998 Bronson, Gary A First Book of C++ West Publishing Company, 1995 Cluts, Nancy Winnick Programming the Windows 95 User Interface Microsoft Press, 1995 Coelho, Rohan, and Maher Hawash DirectX, RDX, RSX, and MMX Technology Addison-Wesley, 1998 Conger, James L Windows API Bible: the Definite Programmer's Reference Waite Group, 1992 Cooper, Alan About Face: Essentials of User Interface Design IDG Books, 1995 Egerton, P A., and W S Hall Computer Graphics: Mathematical First Steps Prentice Hall, 1999 Ezzell, Ben, and Jim Blaney Windows 98 Developer's Handbook Sybex, 1998 Foley, James D., Andries van Damm, Steven K Feiner, and John F Hughes Computer Graphics: Principles and Practice Addison-Wesley, 1997 Glidden, Rob Graphics Programming with Direct3D Addison-Wesley, 1997 Giambruno, Mark 3D Graphics & Animation New Riders, 1997 Giesecke, Frederick E, et al Engineering Graphics Fourth Edition Macmillan, 1987 Hearn, Donald, and M Pauline Baker Computer Graphics Prentice-Hall, 1986 Hearn, Donald, and M Pauline Baker Computer Graphics: C Version Second Edition PrenticeHall, 1997 Hoggar, S.G Mathematics for Computer Graphics Cambridge, 1992 Kawick, Mickey Real-Time Strategy Game Programming using DirectX 6.0 Wordware, 1999 Kernigham, Brian W., and Dennis M Ritchie The C Programming Language Prentice-Hall, 1978 Kold, Jason Win32 Game Developer's Guide with DirectX Waite GRoup Press, 1997 Kovach, Peter J The Awesome Power of Direct3D/DirectX Manning 1998 Mandelbrot, Benoit B The Fractal Geometry of Nature W.T Freeman and Co., 1982 Microsoft Corporation Programmer's Guide to Microsoft Windows 95 Microsoft Press, 1995 Micosoft Corporation The Windows Interface Guidelines for Software Design Microsoft Press, 1995 Microsoft Corporation DirectX SDK documentation 1998 Microsoft Corporation DirectX SDK documentation 1999 Microsoft Corporation DirectX SDK documentation 1999 Minasi, Mark Secrets of Effective GUI Design Sybex, 1994 Moller, Thomas, and Eric Haines Real-Time Rendering A K Peters Ltd., 1999 Morris, Charles W Signs, Language and Behaviors George Braziller, 1955 O'Rourke, Michael Principles of Three-Dimensional Computer Animation Norton, 1998 Petzold, Charles Programming Windows Fifth Edition Microsoft Press, 1999 Ratner, Peter 3-D Human Modeling and Animation Wiley, 1998 Rector, Brent E and Joseph M Newcomer Win32 Programming Addison-Wesley, 1997 Redmond, Frank E III DCOM: Microsoft Distributed Component Object Model IDG Books, 1997 Rimmer, Steve Windows Bitmapped Graphics McGraw-Hill, 1993 Ritcher, Jeffrey Advanced Windows Third Edition Microsoft Press, 1997 Rogerson, Dale Inside COM Microsoft Press, 1997 Root, Michael, and James Boer DirectX Complete McGraw-Hill, 1999 Salmon, Rod, and Mel Slater Computer Graphics: Systems and Concepts Addison-Wesley, 1987 Sanchez, Julio, and Maria P Canton Space Image Processing CRC Press, 1999 Sanchez, Julio, and Maria P Canton Windows Graphics Programming M & T Books, 1999 Schildt, Herbert C++ The Complete Reference Second Edition McGraw-Hill, 1995 Schildt, Herbert Windows 98 Programming from the Ground Up Osborne, 1998 Simon, Richard Win32 Programming API Bible Waite Group Press, 1996 Stein, Michael L, Eric Bowman, and Gregory Pierce Direct3D Professional Reference New Riders, 1997 Thompson, Nigel 3D Graphics Programming for Windows 95 Microsoft Press, 1996 Timmins, Bret DirectDraw Programmming M & T Books, 1996 Trujillo, Stan High Performance Windows Graphics Programming Coriolis Group Books, 1998 Trujillo, Stan Cutting-Edge Direct3D Programming Coriolis Group Books, 1996 Walmsley, Mark Graphics Programming in C++ Springer, 1998 Watt, Alan, and Mark Watt Advanced Animation and Rendering Techniques: Theory and Practice Addison-Wesley, 1992 Watt, Alan, and Fabio Policarpo The Computer Image Addison-Wesley, 1998 Walnum, Clayton Windows 95 Game SDK Strategy Guide Que, 1995 Young, Michael J Introduction to Graphics Programming for Windows 95: Vector Graphics Using C++ AP Professional, 1996 Zaratian, Beck Microsoft Visual C++ Owner's Manual Version 5.0 Microsoft Press, 1997 Color Plates Color Plate 1: The illustration demonstrates bit-to-color mapping in a raster-scan system, which is discussed in Chapter In this example, we have arbitrarily divided one memory byte into three separate bit fields, which encode the three-color values that determine each individual screen pixel Color Plate 2: The screen snapshot shows specular reflection on the surface of the teapot Notice that the reflected highlights are the color of the incident light, not that of the surface material (see Chapter for more information) The teapot in this example is a model for nonperfect reflectors as described by Phong Bui-Toung Color Plate 3: The screen snapshot in this example shows two renderings of a coffee cup The one on the top is obtained through incremental shading, and the one on the bottom, through ray tracing, which is discussed in Chapter Color Plate 4: Reflected object imaged in ray tracing Color Plate 5: Screen snapshot of the DD Access Demo project program Color Plate 6: The screen snapshot shows a coffee cup to which a red marble texture has been applied The various methods used to apply textures are discussed in Chapter 14 Color Plate 7: In this example, the screen snapshot shows three versions of a teapot image in which the intensity of the ambient light has been increased from 0.1 to 0.8 for all three primary colors The effect of changing the ambient light intensity is discussed in Chapter 15 Mesh color value not assigned Mesh color value (0.0,0.7,0.0) Color Plate 8: If you attempt to render a mesh without setting it to a color attribute the result is an image in shades of gray, as shown in the top part of the example above (see Chapter 15 for more information) The image in the lower part of this example shows the object rendered after the mesh is asigned the color value (0.0,0.7,0.0) Color Plate 9: Building an object by loading individual meshes Color Plate 10: Textured sphere Color Plate 11: Metallic and plastic materials (D3DRM Textures Demo program) ... skill for the DirectX 3D programmer Parts III and IV are devoted to 3D graphics programming in DirectX retained mode Part III introduces 3D graphics and discusses retained mode programming at.. .DirectX 3D Graphics Programming Bible Preface | Part I: The Fundamentals Chapter 1: The PC as a Graphics Machine Chapter 2: Graphics Representation and Modeling Chapter 3: 3D Image Transformations... learn 3D graphics programming, we concentrated on it Other factors that influenced our choice are mentioned in the following section Direct3D: Past and Future In more than one sense 3D graphics programming