Microsoft DirectX 8 Developer FAQ
Microsoft Corporation
February 2001
Summary: This article provides in-depth answers to frequently asked development questions regarding Microsoft DirectX, version 8.0, including sections on Direct3D, DirectSound, and DirectPlay (10 printed pages).
Contents
General DirectX Development IssuesDirect3D General Questions Geometry (Vertex) Processing Performance Tuning Direct3DX Utility LibraryDirectSoundDirectplay
General DirectX Developments Issues
Why do I get SO MANY ERROR Messages WHEN I TRY TO Compile THE Samples?
You probably do not have your include path set correctly. Many compilers, including Microsoft? Visual C ?, include an earlier version of the SDK, so if your include path searches the standard compiler include directories first, you'll get incorrect versions of the header files. to remedy this issue, make sure the include path and library paths are set to search the DirectX include and library paths first. See also the dxreadme.txt file in the SDK. If you install the DirectX SDK and you are using Visual C , The Installer CAN Optionally Set up The include path for you.
I get Linker Errors About Multiple or Missing Symbols for Global Unique Identifiers (Guids), What do I do?
The various GUIDs you use should be defined once and only once. The definition for the GUID will be inserted if you #define the INITGUID symbol before including the DirectX header files. Therefore, you should make sure that this only occurs for one compilation unit. An alternative to this method is to link with the dxguid.lib library, which contains definitions for all of the DirectX GUIDs. If you use this method (which is recommended), then you should never #define the INITGUID symbol.Can I cast a POINTER TO A DIRECTX INTERFACE TO A LOWER VERSION NUMBER?
No. DirectX interfaces are COM interfaces. This means that there is no requirement for higher numbered interfaces to be derived from corresponding lower numbered ones. Therefore, the only safe way to obtain a different interface to a DirectX object is to use the QueryInterface method of Inters Must Derface.
CAN I MIX THE USE OE DIRECTX 8 Components And DirectX 7 Or Earlier Components WITHIN THE SAME APPLICATION?
You can freely mix different components of differing version; for example, you could use DirectPlay 8 with DirectDraw 7 in the same application However, you generally can not mix different versions of the same component within the same application;. For example, you can not mix DirectDraw 7 WITH DIRECT3D 8 (Since The Ssent As DirectDraw Has Been Subsumed Into Direct3D in DirectX 8).
What Do The Return Values from The Release or AddRef Methods Mean?
The return value will be the current reference count of the object. However, the COM specification states that you should not rely on this and the value is generally only available for debugging purposes. The values you observe may be unexpected since various other system objects may be holding references to the DirectX objects you create. For this reason, you should not write code that repeatedly calls Release until the reference count is zero, as the object may then be freed even though another component may still be referencing it.Does it matter IN WHICH ORDER I Release DirectX Interfaces?
It should not matter because COM interfaces are reference counted. However, there are some known bugs with the release order of interfaces in some versions of DirectX. For safety, you are advised to release interfaces in reverse creation order when possible.
What is a smart pointer, and shop i users?
A smart pointer is a C template class designed to encapsulate pointer functionality. In particular, there are standard smart pointer classes designed to encapsulate COM interface pointers. These pointers automatically perform QueryInterface instead of a cast, and handle AddRef and Release for you. Whether you should use them is largely a matter of taste. If your code contains lots of copying of interface pointers, with multiple AddRefs and Releases, then smart pointers can probably make your code neater and less error prone. Otherwise, you can do without them. Visual C Includes A Standard Microsoft COM Smart Pointer, Defined in The "Comdef.h" Header file (Look Up COM_PTR_TIEN THE HELP).
I Have Trouble Debugging My DirectX Application, ANY TIPS?
The most common problem with debugging DirectX applications is attempting to debug while a DirectDraw surface is locked. This situation can cause a "Win16 Lock" on Microsoft Windows? 9x systems, which prevents the debugger window from painting. Specifying the D3DLOCK_NOSYSLOCK flag when locking the surface can usually eliminate this. Windows 2000 does not suffer from this problem. When developing an application, it is useful to be running with the debugging version of the DirectX runtime (selected when you install the SDK), which performs some parameter validation and outputs Useful messages to the debugger Output.what's the Correct Way To Check Return Codes?
Use the succeeded and failed macros. DirectX Methods Can Return Multiple Success And Failure Codes, SO A Simple "== D3D_OK" OR Similar Test Will NOT ALWAYS SUFFICE.
What happened to DirectDraw?
Much of the functionality of DirectDraw has now been subsumed into the new Direct3D8 interfaces. Developers working on purely 2D applications may wish to continue using the old DirectX 7 interfaces. Developers working on 3D applications with some 2D elements are encouraged to use Direct3D alternatives (point SPRITES AND BILLBOARD TEXTURES, FOR EXAMPLE) AS this Will Result In Improved Performance and flexibility.
How do I Disable Alt Tab and Other Task Switching?
You don't. Really.
Is there a recommented book evlaining?
Inside COM by Dale Rogerson, published by Microsoft Press, is an excellent introduction to COM. For a more detailed look at COM, the book Essential COM by Don Box, published by Longman, is also highly recommended.
What Books Are there About General Windows Programming?
Lots. However, The Ons That Are Highly Recommended Are: Programming Windows By Charles Petzold (Microsoft Press) Advanced Windows by Jeffrey Richter (Microsoft Press)
Direct3D
General Questions
WHERE CAN I FIND INFORMATION ABOUT 3D Graphics Techniques?
The standard book on the subject is Computer Graphics: Principles and Practice by Foley, Van Dam et al, and is a valuable resource for anyone wanting to understand the mathematical foundations of geometry, rasterization, and lighting techniques The FAQ for the comp... Graphics.algorithms UseNet Group Also Contains Useful Material.
Does Direct3D Emulate FunctionAlity Not Provided by Hardware?
.. It depends Direct3D has a fully featured software vertex processing pipeline (including support for custom vertex shaders) However, no emulation is provided for pixel level operations; applications must check the appropriate caps bits and use the ValidateDevice API to determine support.
Is there a software rasterizer inclined with Direct3D?
No. Direct3D Now Supports Plug-in Software Raster Zers. However, There Is Currently No Software Rasterizer Supplied by DEFAULT.
Does The Direct3D Geometry Code Utilize 3Dnow! And / or Pentium III SIMD INSTRUCTIONS?
Yes. The Direct3D geometry pipeline has several different code paths, depending on the processor type, and will utilize the special floating-point operations provided by the 3DNow! Or Pentium III SIMD instructions where these are available. This includes processing of custom vertex shaders.
How do i prevent transparent pixels being written to the z-buffer?
You can filter out pixels with an alpha value Above or Below a given threshold. You Control this behavior by using the renderstates alphatestenable, alphaaref, and alphafunc.
What is a stencil buffer?
A Stencil Buffer Is An Additional Buffer of Per-Pixel Information, Much Like A Z-Buffer. In Fact, IT Resides in Some of the Bits of A Z-Buffer. Common Steencil / Z-Buffer Formats Are 15-bit z and 1 -bit stencil, or 24-bit z and 8-bit stencil. It is possible to perform simple arithmetic operations on the contents of the stencil buffer on a per-pixel basis as polygons are rendered. For example, the stencil buffer can be incremented or decremented, or the pixel can be rejected if the stencil value fails a simple comparison test. This is useful for effects that involve marking out a region of the frame buffer, and then performing rendering only the marked (or unmarked) region. Good examples Are Volumetric Effects Like Shadow Volumes.
How do I use a steencil buffer to render shadow volume?
The key to this, and other volumetric stencil buffer effects, is the interaction between the stencil buffer and the z-buffer. A scene with a shadow volume is rendered in three stages. First, the scene without the shadow is rendered as usual, using the z-buffer. Next, the shadow is marked out in the stencil buffer as follows. The front faces of the shadow volume are drawn using invisible polygons, with z-testing enabled but z-writes disabled, and the stencil buffer incremented at every Instead.
Now, consider a single pixel. Assuming the camera is not in the shadow volume there are four possibilities for the corresponding point in the scene. If the ray from the camera to the point does not intersect the shadow volume, then no shadow polygons will have been drawn there and the stencil buffer is still zero. Otherwise, if the point lies in front of the shadow volume the shadow polygons will be z-buffered out and the stencil again remains unchanged. If the points lies behind the shadow volume then the same number of front shadow faces as back faces will have been rendered and the stencil will be zero, having been incremented as many times as decremented.The final possibility is that the point lies inside the shadow volume. In this case the back face of the shadow volume will be z-buffered out, but not the front face, so the stencil buffer will be a non-zero value. The result is portions of the frame buffer lying in shadow have non-zero stencil value. Finally, to actually render th e shadow, the whole scene is washed over with an alpha-blended polygon set to only affect pixels with non-zero stencil value. An example of this technique can been seen in the "Shadow Volume" sample that comes with the DirectX SDK.
What Are The TEXEL Alignment Rules? How do I get a one-to-one mapping?
This is explained fully in the DirectX 8 documentation (under the article titled Directly Mapping Texels to Pixels). However, the executive summary is that you should bias your screen coordinates by -0.5 of a pixel in order to align properly with texels. Most cards now conform properly to the texel alignment rules, however there are some older cards or drivers that do not. to handle these cases, the best advice is to contact the hardware vendor in question and request updated drivers or their suggested workaround.What is the purpose Of the d3dcreate_pureDevice flag?
If the D3DCREATE_PUREDEVICE flag is specified during device creation, Direct3D will create a "pure" device. This disables the use of the Get * family of methods, and forces vertex processing to be hardware only. This allows the Direct3D runtime to make certain optimizations that .
How do I use color keying?
DirectX 8 Does Not Support Color Keying. You Should Use Alpha Blending / Testing Instead, Which IS in General a More Flexible Technique That Does Not Suffer from Some of the Problems Associated with color keying.
HOW Do I ENUMERATE THE DISPLAY DEVICES IN A MULTI-MONITOR SYSTEM?
In common with other enumeration functionality, this has moved from being callback based to a simple iteration by the application using methods of the IDirect3D8 interface. Call GetAdapterCount to determine the number of display adapters in the system. Call GetAdapterMonitor to determine which physical monitor an adapter is connected to (this method returns an HMONITOR, which you can then use in the Win32 API GetMonitorInfo to determine information about the physical monitor). Determining the characteristics of a particular display adapter or creating a Direct3D device on that adapter is as simple as passing The appropriate adapter Number in Place of D3DADAPTER_DEFAULT WHEN CALLING GETDEVICECAPS, CREATEDEVICE, or Other Methods.geometry (Vertex) Processing
What happened to the old vertex type like d3dvertex?
The "pre-canned" vertex types are no longer explicitly supported. The multiple vertex stream system allows for more flexible assembly of vertex data. If you want to use one of the "classic" vertex formats, you can build an appropriate FVF code.
Vertex Streams Confuse ME, How do they work?
Direct3D assembles each vertex that is fed into the processing portion of the pipeline from one or more vertex streams. Having only one vertex stream corresponds to the old pre-DirectX 8 model, in which vertices come from a single source. With DirectX 8, different Vertex Components; for Example, One Vertex Buffer Could Hold Positions and Normals, While A Second Held Color VALUES AND TEXTURE COORDINATES.
What is a vertex shader?
A vertex shader is a procedure for processing a single vertex. It is defined using a simple assembly-like language that is assembled by the D3DX utility library into a token stream that Direct3D accepts. The vertex shader takes as input a single vertex, and a set of constant values, and outputs a vertex position (in clip-space) and optionally a set of colors and texture coordinates which are used in rasterization. Notice that when you have a custom vertex shader, the vertex components no longer have any semantics applied To Them by Direct3D and Vertices Are Simply Arbitrary Data That IS Interpreted by The Vertex Shader You Create.DOES A VERTEX SHADER Perform Perspective Division or Clipping?
No. The Vertex Shader Outputs a Homogenous Coordinate In Clip-Space for the Transformed Vertex Position. Perspective Division and Clipping IS Performed Automatical Post-Shader.
Can I Generate Geometry with a Vertex Shader?
A vertex shader can not create or destroy vertices;. It operates on a single vertex at a time, taking one unprocessed vertex as input and outputting a single processed vertex It can therefore be used to manipulate existing geometry (applying deformations, or performing skinning operations) But Cannot Actually Generate New Geometry Per SE.
CAN I Apply a CUSTOM VERTEX SHADER TO THE RESUS OF THE FIXED-FUNCTION GEOMETRY PIPELINE (OR VICE-VERSA)?
No. You Have to Choose One or the Other. If you are for useing a customer..
Can I use a custom vertex shader if my hardware does not support?
YES. The Direct3D Software Vertex-Processing Engine Fully Supports Custom Vertex Shaders with a surprisingly High level of Performance.
How do I determine if the hardware supports my custom vertex shader? Devices capable of supporting vertex shaders in hardware are required to fill out the D3DCAPS8 :: VertexShaderVersion field to indicate the version level of vertex shader they support. Any device claiming to support a particular Level of Vertex Shader Must Support All Legal Vertex Shaders That Meet The Specification for That Level or Below.
How Many Constant Registers Area Available for Vertex Shaders?
Devices supporting DX8 vertex shaders are required to support a minimum of 96 constant registers. Devices may support more than this minimum number, and can report this through the D3DCAPS8 :: MaxVertexShaderConst field.
CAN I Share Position Data Between Vertices with diffrent texture coordinates?
The usual example of this situation is a cube in which you want to use a different texture for each face. Unfortunately the answer is no, it's not currently possible to index the vertex components independently. Even with multiple vertex streams, all streams are indexed together .
WHEN i Submit An Indexed List of Primitives, Does Direct3D Process All of the Vertices IN THE BUFFER, OR JUST THE ONES I indexed?
When using the software geometry pipeline, Direct3D first transforms all of the vertices in the range you submitted, rather than transforming them "on demand" as they are indexed. For densely packed data (that is, where most of the vertices are used) this is more efficient, particularly when SIMD instructions are available. If your data is sparsely packed (that is, many vertices are not used) then you may want to consider rearranging your data to avoid too many redundant transformations. When using the hardware geometry acceleration, Vertices Are Typically Transformed On Demand As the is is used ?what is an index buffer?
An index buffer is exactly analogous to a vertex buffer, but instead it contains indices for use in DrawIndexedPrimitive calls. It is highly recommended that you use index buffers rather than raw application-allocated memory when possible, for the same reasons as vertex buffers.
I Notice That 32-Bit INDICES Are Now A Supported Type; Can I Use Them on All Devices?
No. You must check the D3DCAPS8 :: MaxVertexIndex field to determine the maximum index value that is supported by the device. This value must be greater than 216-1 (0xffff) in order for index buffers of type D3DFMT_INDEX32 to be supported. In addition Note That Some Devices May Support A Maximum Index Value Less Than 232-1 (0xfffffffff); in this case the application virt respect the limited by the device.
What Restrictions Are The The the $ has the fixed-function pipeline?
The fixed-function pipeline requires that each vertex stream be a strict FVF subset, ordered as per a full FVF declaration. Also, note that you must respect any restriction on the number of streams as reported by the D3DCAPS8 :: MaxStreams field (many current Devices and / or Drivers Only Support a Single Stream) .performance TUNING
How Can I Improve The Performance Of My Direct3D Application?
The Following Area Key Areas to Look at When Optimizing Performance:
Batch size. Direct3D is optimized for large batches of primitives. The more polygons that can be sent in a single call, the better. A good rule of thumb is to aim to average over 100 polygons per call. Below that level you're probably Not getting optimal performance, Above That and you '
re into diminishing returns and potential conflicts with concurrency considerations (see below). State changes. Changing render state can be an expensive operation, particularly when changing texture. For this reason, it is important to minimize as much as possible the number of state changes made per frame. Also, try to minimize changes of vertex or index buffer. Note Changing vertex buffer is no longer as expensive in DirectX 8 as it was with previous versions, but it is still good practice to avoid vertex buffer changes where possible. Concurrency . If you can arrange to perform rendering concurrently with other processing, then you will be taking full advantage of system performance. This goal can conflict with the goal of reducing renderstate changes. you need to strike a balance between batching to reduce state changes and pushing Data Out to the Driver Early to Help Achieve Concurrency. Using Multiple Vertex Buffers In Round-Robin Fashion CAN Help with Concurrence. Texture Uplo ads. Uploading textures to the device consumes bandwidth and causes a bandwidth competition with vertex data. Therefore, it is important to not to over commit texture memory, which would force your caching scheme to upload excessive quantities of textures each frame. Vertex and index buffers . You should always use vertex and index buffers, rather than plain blocks of application allocated memory. At a minimum, the locking semantics for vertex and index buffers can avoid a redundant copy operation. With some drivers, the vertex or index buffer may be places IN more Optimal Memory (Perhaps in Video or Agp Memory) for access by the hardware. State Macro Blocks.
These were introduced in DX 7.0, and provide a mechanism for recording a series of state changes (including lighting, material and matrix changes) into a macro, which can then be replayed by a single call This has two advantages:. You reduce the call overhead by making one call instead of many. An aware driver can pre-parse and pre-compile the state changes, making it much faster to submit to the graphics hardware. State changes can still be expensive, but using state macros can help reduce at least some of the cost. use only a single Direct3D device. If you need to render to multiple targets, use SetRenderTarget. If you are creating a windowed application with multiple 3D windows, use the CreateAdditionalSwapChain API. The runtime is optimized for a single device And there is a considering speted Penalty for Using Multiple Devices.
Which Primitive Types (Strips, Fans, Lists, And So on) SHOULD I USE?
Many meshes encountered in real data feature vertices that are shared by multiple polygons. To maximize performance it is desirable to reduce the duplication in vertices transformed and sent across the bus to the rendering device. It is clear that using simple triangle lists achieves no vertex sharing , making it the least optimal method. The choice is then between using strips and fans, which imply a specific connectivity relationship between polygons, and using indexed lists. Where the data naturally falls into strips and fans, these are the most appropriate choice, since they minimize the data sent to the driver. However, decomposing meshes into strips and fans often results in a large number of separate pieces, implying a large number of DrawPrimitive calls. For this reason, the most efficient method is usually to use a single DrawIndexedPrimitive Call with a triangle list. An additional advantage of usufactage an indexed list is this connection es only share a single vertex In summary, if your data naturally falls into large strips or fans, use strips or fans;. otherwise use indexed lists.What's a good usage pattern for vertex buffers if I'm generating dynamic data?
Create a vertex buffer using the D3DUSAGE_DYNAMIC and D3DUSAGE_WRITEONLY usage flags, and the D3DPOOL_DEFAULT pool flag. (Also specify D3DUSAGE_SOFTWAREPROCESSING if you are using software vertex processing.) I = 0. Set state (textures, renderstates, and so on). Check if there IS Space In The Buffer, That IS, IE I M <= n? (where m is the number of new vertices). IF Yes, THEN LOCK The VB with D3DLOCK_NOOVERWRITE. THIS TELLS DIRECT3D AND THE DRIVER THATION You Will Be Adding Vertices And Won't be modifying the ones that you previously baped. Therefore, IF A DMA Operation Was in Progress, IT ISN 'interrupted. if No, Goto 11. Fill in The m Vertices At I. Unlock. Call Draw [Indexed] Primitive. For non-indexed primitives use I as the startVertex parameter. For indexed primitives, ensure the indices point to the correct portion of the vertex buffer (it may be easiest to use the BaseVertexIndex parameter of the SetIndices call to achieve this). I = M. Goto 3. OK, SO We are out of space, so let us start with a new VB. We do not want to use the same one because there might be a DMA operation in progress. We communicate to this to Direct3D and the driver by locking the same VB with the D3DLOCK_DISCARD flag. What this means IS "you can give me a new pointer Because I am Done with the old one and don't really." i = 0. goto 4 (or 6) .direct3dx utility library
What File Formats Aresu Supported by THE D3DX Image File Loader Functions?
The D3DX Image File Loader Functions Support BMP, TGA, PNG, JPG, DIB, PPM, and DDS Files.
TEXT RENDERING FUNCTIONS IN D3DX DON 'TOW WORK, What am I doing wrong?
A common mistake when using the ID3DXFont :: DrawText functions is to specify a zero alpha component for the color parameter;. Resulting in completely transparent (that is, invisible) text For fully opaque text, ensure that the alpha component of the color parameter is Fully Saturate (255) .SHOULD I Use ID3DXFONT or THE SDK FRMEWORK CD3DFONT CLASS for FONT RENDERING?
The id3dxfont class is is incapable of handling kerning and complex International Fonts Because. It can there. It. It. It..... ..........
CD3DFont is designed for speed and uses textured primitives to draw the characters. It can only handle simple fonts and does not support the full array of formatting options available to ID3DXFont, but is useful for simple fast displays such as framerate counters and so forth.
For production code, you May Want To Implement your OWN FONT RENDERING Using TEXTURED Primitives and / OR A GDI BASED Scheme with Caching To Avoid Re-Drawing.
DirectSound
Why Do I Get A Burst of Static WHEN My Application Starts Up? I Notice THIS Problem with Other Applications Too.
You probably installed the debug DirectX runtime The debug version of the runtime fills buffers with static in order to help developers catch bugs with uninitialized buffers You can not guarantee the contents of a DirectSound buffer after creation;.. In particular, you can not assume that a buffer WITH BE ZEROED OUT.
DirectPlay
How do I Enssure My GAME WILL WORK PROPERLY WITH NETWORK ADDRESS TRANSTORS (NATS) AND Internet Connection Sharing (ICS) Setups?
NATs and ICS are complex topics that are covered in greater detail in a separate article on MSDN However, the following tips are good general guidelines:. Use a client-server, not peer-to-peer network topology, using the IDirectPlay8Client and IDirectPlay8Server interfaces ..................................
For iSSUES REGARDING Peer-to-Peer Games, Hosting Servers Behind Nats, and Specific Advice for ICS on Various Different Windows Operating Systems, Refer to The More Detailed Documentation.
What is dpnsvr for?
DPNSVR is a forwarding service for enumeration requests that eliminates problems caused by conflicts between port usages for multiple DirectPlay applications. Using DPNSVR allows DirectPlay to select the port to use automatically, while allowing clients to enumerate your game. By default, DirectPlay will use DPNSVR as this generally provides the most flexibility for applications;. however, you can disable it by specifying the DPNSESSION_NODPNSVR flag when you create your session The use of DPNSVR can cause some issues with NATs on the client-side, specifically, if the client enumerates the host Using the dpnsvr port, and the host responds sale it.................
Why does IDirectplay8lobbyclient :: Initialize Return DPNERR_NOTALLOWED?
DirectPlay Does Not ALLE THAN One Lobby Client or Application Per Process And Attempting To Create Multiple Clients Will Cause This Error To Be Returned.